samedi 5 septembre 2015

How to reuse connect function database java mysqlite?

I'm writing an application with java form and sqlite and I have a function to connect to database and get data like this:

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

Why when I call it in main function I get an error?

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)

I want to everytime run a any query I can use getResultSet() function and pass query into it. I can't write a code like this http://ift.tt/1KxW7MW, each time I need to write a query I do try{} catch{}, final{}. It's hard!

Aucun commentaire:

Enregistrer un commentaire