zoukankan      html  css  js  c++  java
  • Java使用MyBatis的ScriptRunner执行SQL脚本

    脚本文件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();
    	}
    }
    
    
  • 相关阅读:
    sql 读取txt 文件内容,并写入sql的方法
    Thread.Mutex 互斥体
    SQL语句创建登录名,数据库用户,数据库角色及分配权限:
    倾国倾城 歌词
    LINUX下c/c++的学习(4)linux file and direction(stat fstat lstat access umask chmod ...)
    飞蛾扑火
    生成验证码点击可刷新
    C#项目调用非托管代码函数的方法
    【学习】数据库事务
    如何判断数据库是否存在
  • 原文地址:https://www.cnblogs.com/zifeiy/p/10130748.html
Copyright © 2011-2022 走看看