如何重用连接函数数据库java mysqlite?

时间:2015-09-06 01:39:09

标签: java sqlite

我正在编写一个使用java form和sqlite的应用程序,我有一个连接到数据库并获取如下数据的函数:

public ResultSet getResultSet(String query) {
    Connection conn = null;
    ResultSet rs = null;
    try {
        // create a database conn
        conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\nguye_000\\Desktop\\qlct.db");

        Statement statement = conn.createStatement();
        statement.setQueryTimeout(30);

        rs = statement.executeQuery(query);
        return rs;
    }
    catch(SQLException e) {
      // if the error message is "out of memory", 
      // it probably means no database file is found
      System.err.println(e.getMessage());
    }
    finally {
      try {
        if(conn != null)
          conn.close();
      }
      catch(SQLException e) {
        // conn close failed.
        System.err.println(e);
      }
    }
    return rs;
}

为什么当我在main函数中调用它时出现错误?

Database db = new Database();
ResultSet rs = db.getResultSet("SELECT * FROM qlct_options");
while(rs.next()) {
    // read the result set
    System.out.println("id = " + rs.getInt("option_id"));
    System.out.println("name = " + rs.getString("option_key"));
    System.out.println("value = " + rs.getString("option_value"));
}
id = 0
name = null
value = null
Exception in thread "main" java.sql.SQLException: [SQLITE_MISUSE]  Library used incorrectly (out of memory)
    at org.sqlite.core.DB.newSQLException(DB.java:890)
    at org.sqlite.core.DB.newSQLException(DB.java:901)
    at org.sqlite.core.DB.throwex(DB.java:868)
    at org.sqlite.jdbc3.JDBC3ResultSet.next(JDBC3ResultSet.java:83)
    at qlct.Qlct.main(Qlct.java:18)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

我想每次运行任何查询我都可以使用getResultSet()函数并将查询传递给它。我无法编写像http://chuoidichvu.com/downloads/Database.java这样的代码,每次我需要编写查询时,我都会尝试{} catch {},final {}。很难!

1 个答案:

答案 0 :(得分:0)

在关闭连接后(在ResultSet外部的finally部分),您从函数返回try

这会导致错误,因为您可以在ResultSetStatement仍处于打开状态时扫描Connection

要获得您的目标(“重用连接函数数据库java mysqlite”),您必须“重新排列”您尝试定义的抽象。例如,你可以向你的方法传递一个lambda expression(如果你使用的是Java 8)来处理里面的结果