SQLite:结果集游标已经在stmt.executeQuery()之后结束

时间:2013-03-12 14:46:12

标签: sqlite cursor resultset

我正在使用命令allCustomers = stmt.executeQuery("SELECT * FROM customers");

从SQLite数据库读入ResultSet

customers有3列:customerIDfirstnamelastname customerID是0到199之间的整数。

在我的代码中做了一些其他的事情后,我来到了这一行:

if(alleKunden.next()){
    System.out.println( allCustomers.getInt(1) + " " + allCustomers.getString(2));
}

在这一行中,我收到column 2 out of bounds [1,1]错误。如果我放弃 allCustomers.getString(2)输出将为200,并且在下一次迭代中(因为这在for循环中发生),异常ResultSet closed将终止该程序。

我使用firefox插件SQLite检查了数据库,发现数据库正确包含了所有客户信息。

那么为什么我的ResultSet中没有第二列,为什么我得到“200”作为allCustomers.getInt(1)的结果

这是我的全部代码:
(注意:由于某些原因,完全相同的事情在第一个任务createCustomers()

中正常工作
package telefonbook;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class SqlDB {

    private static final SqlDB dbcontroller = new SqlDB(Application.VERBOSE_MODE, Application.CREATE_NEW_DATA, Application.FAKTOR, Application.DB_PATH);
    private static Connection connection;
    private static final String DB_PATH = System.getProperty("user.home") + "/" + "tmp/telefonbook.sqlite";

    static boolean verboseMode;
    static boolean createNewData;
    static int faktor;
    static String dbPath;

    static {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            System.err.println("Error with the JDBC driver");
            e.printStackTrace();
        }
    }

    public SqlDB(boolean verboseMode, boolean createNewData, int faktor, String dbPath){
        this.verboseMode = verboseMode;
        this.createNewData = createNewData;
        this.faktor = faktor;
        this.dbPath = dbPath;
    }

    public static SqlDB getInstance(){
        return dbcontroller;
    }

    private void initDBConnection() {
        try {
            if (connection != null)
                return;
            System.out.println("Creating Connection to Database...");
            connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
            if (!connection.isClosed())
                System.out.println("...Connection established");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                try {
                    if (!connection.isClosed() && connection != null) {
                        connection.close();
                        if (connection.isClosed())
                            System.out.println("Connection to Database closed");
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void createCustomers(int customerAmount) {
        try {
            System.out.print("Creating customers...\n ");

            Statement stmt = connection.createStatement();
            stmt.executeUpdate("DROP TABLE IF EXISTS customer;");
            stmt.executeUpdate("CREATE TABLE customer (customerID, lastname, firstname);");
            String  firstname;
            String lastname;

            for (int i = 0; i < customerAmount; i++){
                    //here a random name is generated. Gonna skip this code
                    firstname = randomname();
                    lastname = randomname();

                    stmt.execute("INSERT INTO customer (customerID, lastname, firstname) VALUES (" + i + ",'" + lastname + "','" + firstname + "')");
            }
            connection.commit();
            if(verboseMode){
                ResultSet allCustomers = stmt.executeQuery("SELECT * FROM customer");
                while(allCustomers.next()){
                    System.out.println(allCustomers.getString(1) + "\t" + allCustomers.getString(2) + "\t" +allCustomers.getString(3));
                }
            }   
        } catch (SQLException e) {
            System.err.println("Couldn't handle DB-Query");
            e.printStackTrace();
        }
    }


    private void createTelefone(int telefonAmount) {
        try {
            String  telefonnumber;
            System.out.print("Creating telefones...\n ");
            Statement stmt = connection.createStatement();
            stmt.executeUpdate("DROP TABLE IF EXISTS telefone;");
            stmt.execute("CREATE TABLE telefone (telefonID, telefonnumber, ownerID);"); 
            ResultSet allCustomers = stmt.executeQuery("SELECT * FROM customer");
            int customerAmount = stmt.executeQuery("SELECT COUNT(*) FROM customer").getInt(1);

            for (int i = 0; i < telefonAmount; i++){
                telefonnumber = randomNumber();
                if(allCustomers.next()){
                    // This line will fail!
                    System.out.println(allCustomers.getInt(1) + " " + allCustomers.getString(2));
                    stmt.execute("INSERT INTO telefone (telefonID, telefonnumber, ownerID) VALUES (" + i + ",'" + telefonnumber + "', " + allCustomers.getInt(1) + ")");
                } else {
                    //do something else
                }
            }
            ResultSet allTelefones = stmt.executeQuery("SELECT * FROM telefone");
            if(verboseMode){
                while(allTelefones.next()){
                    System.out.println(allTelefones.getString(1) + "\t" + allTelefones.getString(2) + "\t" +allTelefones.getString(3));
                }
            }
        } catch (SQLException e) {
            System.err.println("Couldn't handle DB-Query");
            e.printStackTrace();
        }
    }



    public static void Application() {
        int customerAmount = 100*faktor;
        int telefonAmount = 100*faktor;

        SqlDB dbc = SqlDB.getInstance();
        dbc.initDBConnection();
        try{
            connection.setAutoCommit(false);
            if (createNewData){
                dbc.createCustomers(customerAmount);
                dbc.createTelefone(telefonAmount);
            }
        connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

最后,我没有找到问题的根源,但找到了解决方法。

首先,我(由于某些原因,我无法弄清楚)取消注释以下行。

int customerAmount = stmt.executeQuery("SELECT COUNT(*) FROM customer").getInt(1);

之后我替换了行中的stmt.execute

stmt.execute("INSERT INTO telefone (telefonID, telefonnumber, ownerID) VALUES (" + i + ",'" + telefonnumber + "', " + allCustomers.getInt(1) + ")");

以下列方式使用java.sql.PreparedStatement

PreparedStatement prep = connection.prepareStatement("INSERT INTO telefone VALUES(?,?,?);");
prep.setInt(1, i); // telefonID
prep.setString(2, telefonnumber); // telefonnumber
prep.setInt(3, randomOwner); // ownerID
prep.addBatch();