简体   繁体   中英

Using a single JDBC connection for multiple databases

I have a JDBC connection to a SQLite database. After I get the information from the first database (productLine.db) I want to switch the connection to shipMethods.db and read a table from that database. I am currently getting the error:

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

I checked the database and the table is there. Do I need to create a new connection variable or am I doing something wrong?

Code below:

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

The Statement that you're using belongs to the old connection. (You have two active connections; how else should the computer know which one to use?)

Create a new statement from the new connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM