码迷,mamicode.com
首页 > 数据库 > 详细

java程序执行SQL脚本文件

时间:2014-07-24 22:58:14      阅读:307      评论:0      收藏:0      [点我收藏+]

标签: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"));

java程序执行SQL脚本文件,布布扣,bubuko.com

java程序执行SQL脚本文件

标签:style   blog   http   java   color   使用   os   文件   

原文地址:http://www.cnblogs.com/xiaowu-005/p/3866491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!