注意: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');
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/35667.html