我有以下代码:
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);
}
这给了我:
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)
对我来说,一切似乎都没问题。我可以使用连接池连接到数据库,但我不明白上述错误。
答案 0 :(得分:0)
@Mr Morgan,
使用PreparedStatement而不是Statement,意味着替换
ResultSet rs = stmt.executeQuery(query);
与
ProblemStatement pStmt = dbConnection.prepareStatement(query);
ResultSet r = pStmt.executeQuery();
这样做后请显示你的输出!
答案 1 :(得分:0)
在语句末尾删除semicolomn ; 符号:
String query = ("SELECT PersonNo, Forename, Surname FROM Person");
然后在 OnLineLibrary 数据库中直接执行相关查询以检查其输出以及语法是否正确:
SELECT PersonNo, Forename, Surname FROM Person