如何在java中运行sql脚本

时间:2016-12-01 09:23:40

标签: java sql jdbc

在Java中运行sql脚本的最佳方法是什么?我有我与数据库的连接,并选择了一些我认为可能会运行脚本的代码,目前正在获取一些错误。

public class DatabaseConnection {

private String userName = "";
private String password = "";
private String serverName = "";
private String portNumber = "";




public Connection getConnection() throws SQLException {

    Connection conn = null;

    Properties connectionProps = new Properties();
    connectionProps.put("user", this.userName);
    connectionProps.put("password", this.password);
    String connectionString = "jdbc:mysql://" +
            this.serverName +
            ":" + this.portNumber;

    System.out.println("Connection String: " + connectionString);

    conn = DriverManager.getConnection(connectionString, connectionProps);

    System.out.println("Connected to database");
    return conn;


    **ScriptRunner runner = new ScriptRunner(conn, connectionString, connectionProps)
    String file = "resources/cleanDatabaseScript.sql";
    System.out.println("retreived script");
    runner.runScript(new BufferedReader(new FileReader(file)));**


}

ScriptRunner部分是我目前正在努力的领域。

1 个答案:

答案 0 :(得分:2)

这是连接到mySql的基本类:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DbConnection {

    private static Connection singleConnection ;
    private static Statement  singleStatement;


    public static synchronized Statement getStatement() throws SQLException{

        if (singleConnection == null){
            singleConnection = DriverManager.getConnection("jdbc:mysql://HereTheHost:HereThePortNumber/HereTheDataBaseName","HereTheUserName","HereThePassWord");
            if (singleStatement == null){
                singleStatement = singleConnection.createStatement();
                System.out.println("Connection Success !");
            }
        }
        return singleStatement;
    }

}

此示例确保您只有一个数据库连接实例,如果您不理解,只需忽略它。