0

我有一个 Java 应用程序,我需要它使用 JDBC 连接我的 MySQL 数据库的 SQL 脚本。

这是我的 Java 应用程序:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package basic;
import basic.ScriptRunner;
import javax.swing.*;
import java.sql.*;
import java.io.*;

/**
 *
 * @author User
 */
public class javaconnect {
    Connection conn = null;
    public static Connection ConnectDb(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/new","login","pass");
/*As we are creating a connection on a local computer we will write the url as jdbc:mysql://localhost:3306 */
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.runScript(new BufferedReader(new FileReader("D://Java Lenti/EkonomiSoftware/src/basic/new.sql")));

return conn ;
}
catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
return null;}


}

}

问题是 Java 应用程序通过 MySQL 服务器连接,而不是通过 SQL 脚本。我认为问题出在我给出的连接参数上。谁能指导我如何更改连接以使其连接到 SQL 脚本而不是服务器?

4

1 回答 1

0

它对我有用:

package com.spring.sample.controller;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;

public class Main {

    public static void main(String[] args) {
        try {

            Class.forName("com.mysql.jdbc.Driver");

            Connection conn = (Connection) DriverManager
                    .getConnection(
                            "",
                            "", "");

            ScriptRunner runner = new ScriptRunner(conn, false, false);
            runner.runScript(new BufferedReader(new FileReader("new.sql")));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

新的.sql

insert into hello(name) values ('test');

可能是你的 sql 文件有一些错误。

于 2013-10-29T12:40:47.280 回答