您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在我的第一个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);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。