栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaFX程序初次运行创建数据库并执行建表SQL详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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);
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/137397.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号