脚本文件D:/test_transaction.sql
:
start transaction;
drop table if exists testdb.test_transaction_table;
create table testdb.test_transaction_table select table_name from information_schema.tables;
commit;
依赖maven坐标:
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
示例程序:
package com.zifeiy.test.normal;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
public class RunScriptTest {
private static String APPENDED_DB_INFO
= "?useUnicode=true&characterEncoding=UTF8"
+ "&rewriteBatchedStatements=true"
+ "&useLegacyDatetimeCode=false"
+ "&serverTimezone=Asia/Shanghai"
+ "&useSSL=false";
private static String className = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/testdb" + APPENDED_DB_INFO;
private static String username = "root";
private static String password = "password";
private static Connection connection = null;
public static void main(String[] args) throws ClassNotFoundException, SQLException, FileNotFoundException {
Class.forName(className);
connection = DriverManager.getConnection(url, username, password);
ScriptRunner scriptRunner = new ScriptRunner(connection);
Resources.setCharset(Charset.forName("UTF8"));
// scriptRunner.setLogWriter(null);
scriptRunner.runScript(new FileReader(new File("D:/test_transaction.sql")));
scriptRunner.closeConnection();
connection.close();
}
}