java执行项目中的sql文件

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值