Java执行SQL脚本文件到数据库详解
本文实例为大家分享了Java执行SQL脚本文件到数据库的具体方式,供大家参考,具体内容如下
方式一:直接读取SQL脚本文件的内容,然后传递到SQL中。
代码:RunSqlService:
@Autowired
privateRunSqlDaorunSqlDao;
/**
*读取文件内容到SQL中执行
*@paramsqlPathSQL文件的路径:如:D:/TestProject/web/sql/脚本.Sql
*/
publicvoidrunSqlByReadFileContent(StringsqlPath)throwsException{
try{
StringsqlStr=readFileByLines(sqlPath);
//System.out.println("获得的文本:"+sqlStr);
if(sqlStr.length()>0){
runSqlDao.runSqlBySqlStr(sqlStr);
}
}catch(Exceptione){
e.printStackTrace();
throwe;
}
}
/**
*以行为单位读取文件,常用于读面向行的格式化文件
*/
privateStringreadFileByLines(StringfilePath)throwsException{
StringBufferstr=newStringBuffer();
BufferedReaderreader=null;
try{
reader=newBufferedReader(newInputStreamReader(
newFileInputStream(filePath),"UTF-8"));
StringtempString=null;
intline=1;
//一次读入一行,直到读入null为文件结束
while((tempString=reader.readLine())!=null){
//显示行号
//System.out.println("line"+line+":"+tempString);
str=str.append(""+tempString);
line++;
}
reader.close();
}catch(IOExceptione){
e.printStackTrace();
throwe;
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOExceptione1){
}
}
}
returnstr.toString();
}
RunSqlDao:
/**
*@paramsqlStr
*/
publicvoidrunSqlBySqlStr(StringsqlStr){
Mapmap=newHashMap();
map.put("sqlStr",sqlStr);
sqlSessionTemplate.selectList("runSql.runSqlBySqlStr",map);
}
SQLMap:
这种写法:只支持数据的变化(新增、修改、删除),且SQL文件内容以begin开始,以end结束。无法更新表字段修改等操作。
方式二;使用ScriptRunner
代码:RunSqlService:
/**
*执行sql脚本文件使用ScriptRunner
*@paramsqlPathSQL文件的路径:如:D:/TestProject/web/sql/脚本.Sql
*/
publicvoidrunSqlByScriptRunner(StringsqlPath)throwsException{
try{
SqlSessionsqlSession=sqlSessionFactory.openSession();
Connectionconn=sqlSession.getConnection();
ScriptRunnerrunner=newScriptRunner(conn);
runner.setEscapeProcessing(false);
runner.setSendFullScript(true);
runner.runScript(newInputStreamReader(newFileInputStream(sqlPath),"UTF-8"));
}catch(Exceptione){
e.printStackTrace();
throwe;
}
}
这种写法:只能有一行SQL,即一次执行一个SQL语句,否则就会报错。
方式三:使用ScriptUtils
代码:RunSqlService:(以下两种方式:脚本.Sql和RunSqlService在同一目录下)
方法(1)
/**
*执行sql脚本文件使用Spring工具类
*/
publicvoidrunSqlBySpringUtils()throwsException{
try{
SqlSessionsqlSession=sqlSessionFactory.openSession();
Connectionconn=sqlSession.getConnection();
ClassPathResourcerc=newClassPathResource("脚本.Sql",RunSqlDao.class);
ScriptUtils.executeSqlScript(conn,rc);
}catch(Exceptione){
e.printStackTrace();
throwe;
}
}
方法(2)
/**
*执行sql脚本文件使用Spring工具类
*/
publicvoidrunSqlBySpringUtils()throwsException{
try{
SqlSessionsqlSession=sqlSessionFactory.openSession();
Connectionconn=sqlSession.getConnection();
ClassPathResourcerc=newClassPathResource("脚本.Sql",RunSqlDao.class);
EncodedResourceer=newEncodedResource(rc,"utf-8");
ScriptUtils.executeSqlScript(conn,er);
}catch(Exceptione){
e.printStackTrace();
throwe;
}
}
方法(1),脚本.Sql文件必须是ANSI的,否则执行到数据中汉字是乱码。
方法(2)解决了方法(1)的问题,完美了,喜欢的小伙伴们快拿去享用吧。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。