赞
踩
注意:ant.jar的版本是1.7.
直接看代码:
package com.ilucky.sql;
import java.io.File;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import org.apache.tools.ant.types.EnumeratedAttribute;
/**
* @author IluckySi
* @date 20140603
*/
public class RunSqlScript {
public void runSqlScript() {
SQLExec sqlExec = new SQLExec();
String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "mysql";
sqlExec.setDriver(driverClass);
sqlExec.setUrl(url);
sqlExec.setUserid(username);
sqlExec.setPassword(password);
sqlExec.setSrc(new File("D:/user.sql"));
//如果有出错的语句继续执行.
sqlExec.setOnerror((SQLExec.OnError) (EnumeratedAttribute.getInstance(SQLExec.OnError.class, "continue")));
sqlExec.setPrint(true);
sqlExec.setOutput(new File("D:/userinfo.txt"));
sqlExec.setProject(new Project());
sqlExec.execute();
}
}
然后看测试代码:
package com.ilucky.sql;
/**
* @author IluckySi
* @date 20140603
*/
public class MainTest {
public static void main(String[] args) {
RunSqlScript rsc = new RunSqlScript();
rsc.runSqlScript();
}
}
3.涉及到的sql文件user.sql.
drop database if exists test;
create database test character set utf8;
use test;
create table user (
id varchar(255) unique,
username varchar(255) not null,
password varchar(255) not null
) default charset=utf8;
insert into user values('1', '司冬雪1', 'a');
insert into user values('2', '司冬雪2', 'b');
insert into user values('3', '司冬雪3', 'c');
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。