为多个数据库使用单个JDBC连接

时间:2014-06-03 19:15:21

标签: java sqlite jdbc

我有一个到SQLite数据库的JDBC连接。从第一个数据库(productLine.db)获取信息后,我想将连接切换到shipMethods.db并从该数据库中读取一个表。我目前收到错误:

    SQL error or missing database (no such table: Ground)

我检查了数据库,表格就在那里。我是否需要创建新的连接变量或者我做错了什么?

以下代码:

    //Get connection to database
    try {
        Connection con = DriverManager.getConnection ("jdbc:sqlite:productLine.db");
        //Make statement for interacting with database
        Statement stmt = con.createStatement();

        //Get total weight
        ResultSet rs = stmt.executeQuery ("SELECT Weight FROM Numbers WHERE TYPE = '" + product + "'");
        while (rs.next()) {
            weight = rs.getDouble("weight")*1000;
        }

        //get zone
        rs = stmt.executeQuery ("SELECT ZONE FROM Zones WHERE ZIP = " + shortZip);
        while (rs.next()) {
            zone = rs.getInt("Zone");
        }

        //Change to Ship Methods database
        con = DriverManager.getConnection("jdbc:sqlite:shipMethods.db");

        //Get Price
        rs = stmt.executeQuery ("SELECT EIGHT FROM Ground WHERE WEIGHT = " + weight);
        while (rs.next()) {
            price = rs.getDouble("Cost");
        }

        System.out.println("Weight: " + weight);
        System.out.println("Zone: " + zone);
        System.out.println("Price: " + price);

    } catch(SQLException e) {
        System.out.println("SQL exception occured" + e);
    }

1 个答案:

答案 0 :(得分:4)

您使用的Statement属于旧连接。 (您有两个活动连接;计算机应该如何知道要使用哪个?)

从新连接创建一个新语句。