简体   繁体   中英

Trying to connect to Java Derby database using JDBC

I have the following code:

Connection conn = null;
    Statement stmt = null;

    // MySQL connection details.
    String username = ("username");
    String password = ("password");
    String url = ("jdbc:derby://localhost:1527/OnlineLibrary");

    try {

        // Connect to database. 
        Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();               
        conn = DriverManager.getConnection (url, username, password);            
        stmt = conn.createStatement();

        // Get data.
        String query = ("SELECT PersonNo, Forename, Surname FROM Person;");                       
        ResultSet rs = stmt.executeQuery(query);               
        while (rs.next()) {                
            System.out.println("Person: no: " + rs.getInt("PersonNo") + " name: " + rs.getString("Forename") + " " + rs.getString("Surname"));
        }                 

        // Disconnect from database.
        stmt.close();
        conn.close();
    }
    catch(Exception ex) {
        Java_Utils.printStackTrace("Error connecting to database", ex, true);    
    }        

Which gives me:

Error connecting to database
org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
org.apache.derby.client.am.Statement.executeQuery(Unknown Source)
misc.Simple_JDBC_Test.main(Simple_JDBC_Test.java:32)

Everything seems alright to me. I can connect to the DB using connection pooling but I don't understand the above error.

@Mr Morgan,
Use PreparedStatement instead of Statement, means replace

ResultSet rs = stmt.executeQuery(query);
with

ProblemStatement pStmt = dbConnection.prepareStatement(query);

ResultSet r = pStmt.executeQuery();

after doing this show your output please!

Remove the semicolomn ; sign at the end of your statement:

String query = ("SELECT PersonNo, Forename, Surname FROM Person");

Then execute the related query directely in your OnLineLibrary database to check its output and if its syntax is correct:

SELECT PersonNo, Forename, Surname FROM Person

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