在开发过程中我们有时候会碰到这样的场景,需要代码动态创建数据库并且执行sql初始化脚本,下面给出一个简单的实现类。
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class sqlUtil {
public static void main(String[] args){
String database = "testdb";
new sqlUtil ().getConn(database);
}
String mysqlDriver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mysql";
String newUrl = "jdbc:mysql://localhost:3306/";
String username = "root";
String password = "root";
Connection conn = null;
Connection newConn = null;
public void getConn(String database){
try {
Class.forName(mysqlDriver);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
try{
String databaseSql = "create database " + database;
conn = DriverManager.getConnection(url, username, password);
Statement smt = conn.createStatement();
if (conn != null) {
smt.executeUpdate(databaseSql);
newConn = DriverManager.getConnection(newUrl + database,
username, password);
ScriptRunner runner = new ScriptRunner(newConn);
runner.setErrorLogWriter(null);
runner.setLogWriter(null);
runner.runScript( Resources.getResourceAsReader("dockerpaas.sql"));
conn.close();
newConn.close ();
}
}catch (SQLException e1){
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace ( );
}
}
}
网友评论