msmahon
msmahon

Reputation: 434

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

Upvotes: 1

Views: 1502

Answers (1)

CL.
CL.

Reputation: 180010

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.

Upvotes: 4

Related Questions