简体   繁体   English

尝试使用 JDBC 连接到 Java Derby 数据库

[英]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使用 PreparedStatement 而不是 Statement,意味着替换

ResultSet rs = stmt.executeQuery(query);结果集 rs = stmt.executeQuery(query);
with

ProblemStatement pStmt = dbConnection.prepareStatement(query);问题陈述 pStmt = dbConnection.prepareStatement(query);

ResultSet r = pStmt.executeQuery();结果集 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:然后在您的OnLineLibrary数据库中直接执行相关查询以检查其输出以及其语法是否正确:

SELECT PersonNo, Forename, Surname FROM Person

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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