我在我的代码jdbc中使用编写了以下代码来搜索ID:
public Item findById(String id) {
Item result = null;
String s = "SELECT id, key, name, creat, description FROM trackersql WHERE id = :id";
try (Connection connection = init()) {
PreparedStatement statement = connection.prepareStatement(s);
ResultSet resultSet = statement.executeQuery();
while(resultSet.next()) {
Item item = new Item();
statement.setString(1, id);
statement.setString(2, item.getKey());
statement.setString(3, item.getName());
statement.setLong(4, item.getCreat());
statement.setString(5, item.getDescription());
statement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
以这种方式检查我的代码:
try {
DriverManager.registerDriver(new org.postgresql.Driver());
} catch (SQLException e) {
e.printStackTrace();
}
TrackerSQL trackerSQL = new TrackerSQL();
Item item1 = new Item("1", "1", "test1", 1, "test1");
trackerSQL.init();
System.out.println(trackerSQL.findById(item1.getId()));
但出现以下错误:
错误:语法错误(大约位置:“:”)位置:第69位org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2103)在org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836)在org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)在org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512)在org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)在org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:273)在ru.job4j.trackersql2.TrackerSQL.findById(TrackerSQL.java:104)在ru.job4j.trackersql2.TrackerSQL.main(TrackerSQL.java:188)null
我的错误是什么?
JDBC不知道命名参数。用:id
代替?
。你也永远不会绑定参数
String s = "SELECT id, key, name, creat, description FROM trackersql WHERE id = :id";
try (Connection connection = init()) {
PreparedStatement statement = connection.prepareStatement(s);
statement.setString(1,id)
ResultSet resultSet = statement.executeQuery();