英文:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "-"
问题
public class UserRepo {
private String baseQuery = "SELECT * FROM bank_console.user_credentials ";
public Optional<UserInfo> findUserByCredentials(String username, String password) {
Optional<UserInfo> _user = Optional.empty();
try (Connection conn = ConnectionFactory.getInstance().getConnection()){
String sql = baseQuery +
"WHERE username = ? AND password = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
_user = mapResultSet(rs).stream().findFirst();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return _user;
}
}
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.12</version>
</dependency>
英文:
I have a PostreSQL database which I am trying to access with a Java app. When it comes to the following code:
public class UserRepo {
private String baseQuery = "SELECT * FROM bank-console.user_credentials ";
public Optional<UserInfo> findUserByCredentials(String username, String password) {
Optional<UserInfo> _user = Optional.empty();
try (Connection conn = ConnectionFactory.getInstance().getConnection()){
String sql = baseQuery +
"WHERE username = ? AND password = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
_user = mapResultSet(rs).stream().findFirst();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
return _user;
}
It throws the error message exactly as the question title. When I take the text of the baseQuery and the String sql and enter them in my PostgreSQL app exactly (replacing the question marks with actual values), it retrieves the table perfectly. Where is the syntax error here?
My pom file contains
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.12</version>
</dependency>
答案1
得分: 0
作为对 @Mike Organek 评论的回应,答案是 bank-console 不应该有连字符。使用双引号并没有起作用,因为 baseQuery 已经在双引号内部。单引号本身就是语法错误。所以有效的做法是将 bank-console 更改为 bankconsole。我的 SQL 应用允许我这样做而不丢失表格。然后相应地修改 baseQuery。
英文:
In response to @Mike Organek's comment, the answer is that bank-console should not have a hyphen. Using double-quotes did not work because the baseQuery is already within double quotes. Single-quotes was a syntax error in itself. So what worked was to change bank-console to bankconsole. My SQL app allowed me to do that without losing the tables. Then just change the baseQuery accordingly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论