【问题标题】:Derby DB table creation and connectionDerby DB 表创建和连接
【发布时间】:2018-07-16 22:53:31
【问题描述】:

我正在编写一组基于 Eclipse 控制台的文字游戏,并集成了一个嵌入式 Derby DB 驱动程序来存储用户结果历史记录。

我的问题是关于 Derby 表的初始化。

Derby 数据库连接本身有一个条件检查器: "jdbc:derby:dbName;create=true" 所以如果数据库存在,它会连接,如果不存在,它会创建。

我被困在如何使用数据库中的 TBL 执行此操作。即使在这个类似问题的帮助下:how to create table if it doesn't exist using Derby Db

我在下面包含了我的代码。我的代码在查询表“RPS”时抛出了一个 sql 异常。 (我的 dbName 是“RPSdb”,TBL 名称是“RPS”。)

此异常被我的 catch 块捕获并传递给不同类(“DerbyHelper”)中的静态方法。这个静态方法现在设置为暂时总是返回true。

我的问题是如何编写我的 catch 块和相应的辅助类,以便实现上述 TBL 功能?

 Connection conn = null;
 ArrayList<Statement> statements = new ArrayList<Statement>(); // list of Statements, PreparedStatements
 Statement s;
 ResultSet rs = null;

    try {
             conn = DriverManager.getConnection(protocol + dbName + ";create=true");

             conn.setAutoCommit(false);

             s = conn.createStatement();
             statements.add(s);

             rs = s.executeQuery("select * from RPS");
             rs.next();
             int cG = rs.getInt(1) + corGuess;
             int iCG = rs.getInt(2) + inCorGuess;

             s.executeUpdate("UPDATE RPS SET corGuesses = " + cG 
                     + ", inCorGuesses= " + iCG);

             conn.commit();

         }
         catch( SQLException e ) {
            if( DerbyHelper.tableAlreadyExists( e ) ) {
               // what do I do here??
            }
        }

【问题讨论】:

    标签: java jdbc derby


    【解决方案1】:

    接口java.sql.Connection 有方法getMetaData(),它返回java.sql.DatabaseMetaData,并且该接口包含方法getTables(),它会告诉你你的数据库表是否存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      相关资源
      最近更新 更多