在Java中執行SQL指令碼總結
阿新 • • 發佈:2019-02-01
利用 Ant 的SQL Task來實現執行SQL 指令碼的功能。
ant 包中的 SQLExec類的擴充套件,此時需要將ant 包(ant.jar)匯入
java 建立資料庫
ant 包中的 SQLExec類的擴充套件,此時需要將ant 包(ant.jar)匯入
SQLExec sqlExec = new SQLExec(); String mysqlDriver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/mysql"; String username = "root"; String password = ""; // 設定資料庫引數 sqlExec.setDriver(mysqlDriver); sqlExec.setUrl(url); sqlExec.setUserid(username); sqlExec.setPassword(password); //設定sql指令碼 sqlExec.setSrc(new File("g:\\lite_basic_db.sql")); sqlExec.setPrint(true); // 設定是否輸出 sqlExec.setProject(new Project()); // 要指定這個屬性,不然會出錯 sqlExec.execute();
java 建立資料庫
String mysqlDriver = "com.mysql.jdbc.Driver"; String newUrl = "jdbc:mysql://localhost:3306/"; String username = "root"; String password = ""; Connection conn = null; public Connection getConn() { try { Class.forName(mysqlDriver); conn = DriverManager.getConnection(newUrl, username, password); if (conn != null) { Statement newSmt = conn.createStatement(); int i = newSmt.executeUpdate("CREATE DATABASE lite_basic_db;");// DDL語句返回值為0;建立資料庫 if (i == 0) { System.out.println("建立成功!"); } newSmt.execute("USE lite_basic_db;");//開啟 轉向資料庫 } } catch (Exception e) { e.printStackTrace(); } return conn; }
- 下載次數: 6