JavaFX程式初次執行建立資料庫並執行建表SQL
阿新 • • 發佈:2018-11-29
在我的第一個JavaFX程式完成安裝的時候才突然發現,不能要用這個軟體還要手動執行Sql來建表吧?
於是我的想法是在Main程式中執行時檢測資料庫連線狀況,如果沒有檢測到資料庫或者連線異常,那麼出現錯誤提示,如果資料庫連線沒有問題那麼自動建立資料庫並執行建表Sql進行初始化。
package oa.util; import java.io.IOException; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.apache.ibatis.jdbc.ScriptRunner; import com.ibatis.common.resources.Resources; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class CreateMySqlDatabase { public static void createDatabase() throws SQLException { Connection conn; conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "1234"); Statement stmt = (Statement) conn.createStatement(); String sql = "CREATE DATABASE UTILITY"; stmt.executeUpdate(sql); } public static void executeSql() throws IOException, SQLException { Properties props = Resources.getResourceAsProperties("mysql.properties"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); Connection conn = (Connection) DriverManager.getConnection(url, username, password); ScriptRunner runner = new ScriptRunner(conn); runner.setErrorLogWriter(null); runner.setLogWriter(null); runner.runScript(Resources.getResourceAsReader("sql/utility.sql")); conn.close(); System.out.println("==SUCCESS=="); } }
需要用到 ibatis-common-2.jar讀取mysql.properties檔案中的JDBC資訊。
MAIN做判斷:
try { DriverManager.getConnection("jdbc:mysql://localhost:3306/utility", "root", "1234"); isError = false; } catch (MySQLSyntaxErrorException e) { primaryStage.setTitle("正在建立Utility資料庫……"); Label error = new Label("正在建立Utility資料庫……"); error.setFont(new Font("Cambria", 100)); Pane pane = new Pane(); pane.getChildren().add(error); Scene scene = new Scene(pane); primaryStage.setScene(scene); primaryStage.show(); try { CreateMySqlDatabase.createDatabase(); CreateMySqlDatabase.executeSql(); isError = false; primaryStage.close(); } catch (SQLException | IOException e1) { primaryStage.close(); e1.printStackTrace(); } } catch (SQLException se) { Thread.sleep(3000); primaryStage.close(); se.printStackTrace(); } if (!isError) { run(); } } public static void main(String[] args) { launch(args); }