Mybatis批量执行SQL文件中的语句(在Spring环境中):
@Autowired
private SqlSession sqlSession;
InputStreamReader reader = file2Reader(file);
//批量执行文件中的SQL语句
batchExecuteSqlFromFile(reader);
/**
* 文件转成Reader
* @param file
* @return
*/
private InputStreamReader file2Reader(MultipartFile file)
{
InputStreamReader reader = null;
try
{
InputStream inputStream = file.getInputStream();
// result = IOUtils.toString(inputStream,"UTF-8");
reader = new InputStreamReader(inputStream, "utf-8");
logger.info("------------------------------" + reader);
}
catch (IOException e)
{
e.printStackTrace();
}
return reader;
}
/**
* 获取当前Mybatis的连接信息
* @return
*/
public Connection getConnection()
{
Connection conn = null;
try
{
conn = sqlSession.getConfiguration().getEnvironment().getDataSource().getConnection();
logger.info("===This Connection isClosed ? " + conn.isClosed());
}
catch (Exception e)
{
e.printStackTrace();
}
return conn;
}
/**
* 批量更新文件中的SQL
* @param reader
*/
private void batchExecuteSqlFromFile(InputStreamReader reader)
{
try
{
Connection connection = getConnection();
ScriptRunner scriptRunner = new ScriptRunner(connection);
scriptRunner.setLogWriter(null);
scriptRunner.setErrorLogWriter(null);
scriptRunner.setSendFullScript(true);// true执行所有代码,否则按行识别代码
scriptRunner.setAutoCommit(true);
scriptRunner.runScript(reader);
scriptRunner.closeConnection();
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}