import java.sql.*; import java.util.List; public class DBConnection { public Connection getConnection(){ Connection con=null; try { Class.forName("com.mysql.jdbc.Driver"); con= DriverManager.getConnection("jdbc:mysql://10.30.10.124:3306/sati_code","root","123456" ); } catch (ClassNotFoundException e) { System.out.println("没有找到数据库驱动"); } catch (SQLException e) { System.out.println("数据库连接失败"); } return con; } public static void close(Connection con){ if(con!=null){ try { con.close(); } catch (SQLException e) { System.out.println("数据库关闭异常"); } } } public boolean executeBatchByStatement(ListsqlList) { Connection conn=null; boolean ret = false; if (conn != null) { Statement stmt = null; try { conn.setAutoCommit(false); stmt = conn.createStatement(); for (String s : sqlList) { stmt.addBatch(s); } stmt.executeBatch(); conn.commit(); ret = true; } catch (BatchUpdateException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.setAutoCommit(true); if (stmt != null) { stmt.close(); stmt = null; } } catch (SQLException e) { e.printStackTrace(); } } } return ret; } }
2.SQL工具类
import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.EncodedResource; import org.springframework.jdbc.datasource.init.scriptUtils; import org.springframework.stereotype.Component; import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.*; @Component public class ExecuteSQLUtil { public boolean readSQLFile(InputStreamReader fileReader) { BufferedReader bufferedReader = new BufferedReader(fileReader); try { StringBuilder sBuilder = new StringBuilder(""); String str = bufferedReader.readLine(); while (str != null) { // 去掉一些注释,和一些没用的字符 if (!str.startsWith("#") && !str.startsWith(" @RestController public class TestController { @Autowired ExecuteSQLUtil executeSQLUtil; @PostMapping("/executeMysql") public String executeMysql(@RequestParam(value = "file") MultipartFile serviceFile) { try { //把MultipartFile转成字节流 InputStream inputStream = serviceFile.getInputStream(); //把inputStream 转到 InputStreamReader 用与BufferedReader缓冲流 InputStreamReader fileReader = new InputStreamReader(inputStream,"UTF-8"); executeSQLUtil.readSQLFile(fileReader); } catch (Exception e) { e.printStackTrace(); } return "ok"; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)