一、首先引入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”));