2016-12-01 162 views
-3

嗨在Java中運行sql腳本的最佳方式是什麼?我有我的連接到數據庫,並拿起一些代碼,我認爲可能會運行該腳本目前得到一些錯誤。如何在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部分是im正在努力與當前的區域。

+0

你得到了什麼錯誤? – Janar

+0

目前這在scriptRunner行,但我確實改變了我複製的原始代碼以匹配我的。 錯誤:(47,88)java:';'預計 我添加了conn,connectionString,connectionProps – Peter

+0

爲什麼在'ScriptRunner runner ...'行最後沒有';'? –

回答

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; 
    } 

} 

這個例子可以確保你將有隻有一個數據庫連接的情況下,如果你不明白這只是忽略它。

+0

,並且爲了從您的表格中檢索數據,您可以看到以下示例:https://github.com/Meshredded/Java8_Planning_Manager/blob/master/sources/src/memoryDatabaseExchange/CoursLoader.java – Meshredded

+0

感謝您的評價很多更清潔,但我認爲這一點已被錯過。雖然你已經改善了數據庫連接。我沒有解釋我在我的項目中有一個文件 String file =「resources/cleanDatabaseScript.sql」; 我需要做的就是在數據庫連接後運行腳本。我在原帖中沒有正確解釋我的錯。 – Peter

+0

如果你有一個文件比它必須是一個sqlite數據庫,所以你需要另一個驅動程序 – Meshredded