標籤:style blog http java color 使用 os 檔案
首先引入ibatis-common-2.jar包
import com.ibatis.common.jdbc.ScriptRunner; import com.ibatis.common.resources.Resources;
jpetstore測試代碼如下:
package com.ibatis.jpetstore.test;
import java.sql.DriverManager; import java.util.Properties;
import com.ibatis.common.jdbc.ScriptRunner; import com.ibatis.common.resources.Resources; import com.mysql.jdbc.Connection;
public class DBTestSQL {
public static void main(String[] args) { try { Properties props = Resources.getResourceAsProperties("properties/database.properties"); String url = props.getProperty("url"); String driver = props.getProperty("driver"); String username = props.getProperty("username"); String password = props.getProperty("password"); System.out.println(url); if(url.equals("jdbc:mysql://localhost:3306/jpetstore1")) { Class.forName(driver).newInstance(); Connection conn = (Connection) DriverManager.getConnection(url, username, password); ScriptRunner runner = new ScriptRunner(conn, false, false); runner.setErrorLogWriter(null); runner.setLogWriter(null); runner.runScript(Resources.getResourceAsReader("ddl/mysql/jpetstore-mysql-schema.sql")); runner.runScript(Resources.getResourceAsReader("ddl/mysql/jpetstore-mysql-dataload.sql")); } } catch (Exception e) { e.printStackTrace(); }
}
}
ScriptRunner(com.ibatis.common.jdbc.*)用法ScriptRunner類用於執行SQL語句,例如建立資料庫schema,或傳入預設或測試資料庫等等。從下面的例子可以認識到它的易用性:
例子1:使用現成的資料庫連接
Connection conn=getConnection();//some method to get a Connection
ScriptRunner runner=new ScriptRunner();
runner.runScript(conn,Resources.getResourceAsReader("com/some/resource/path/initialize.sql"));
conn.close();
例子2:使用新的資料庫連接
ScriptRunner runner=new ScriptRunner("com.some.Driver","jdbc:url://db","login","password");
runner.runScript(conn,new FileReader("/user/local/db/scripts/initialize-db.sql"));
例子3:使用新建立的資料連線
Properties props= getProperties();//some properties form somewhere
ScriptRunner runner =new ScriptRunner(props);
runner.runScript(conn,new FileReader("/user/local/db/scripts/initialize-db.sql"));