JavaFX程序初次运行创建数据库并执行建表SQL
在我的第一个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); }