gpt4 book ai didi

java - org.postgresql.util.PSQLException : ERROR: syntax error at or near "7"

转载 作者:行者123 更新时间:2023-12-02 09:30:57 27 4
gpt4 key购买 nike

我正在尝试在我的应用程序中创建私有(private)聊天,但是当我尝试创建表时出现此错误:

org.postgresql.util.PSQLException: ERROR: syntax error at or near "7" Position: 14

代码:

 public static String checkIfChatExists(String code, String friend) throws SQLException {
String i = LoginManager.checkCode(code);
if(i.equals("code-not-exists")) {
return "invalid-code";
}

ResultSet rs = conn.prepareStatement("SELECT * FROM pwchats").executeQuery();
while (rs.next()) {
if(rs.getString("user1").equals(i) && rs.getString("user2").equals(friend) || rs.getString("user1").equals(friend) && rs.getString("user2").equals(i)) {
return "exists";
}
}
PreparedStatement pre = conn.prepareStatement("INSERT INTO pwchats(user1, user2) VALUES(?, ?)");
pre.setString(1, i);
pre.setString(2, friend);
pre.execute();
PreparedStatement getChatId = conn.prepareStatement("SELECT * FROM pwchats WHERE user1 = ? AND user2 = ?;");
getChatId.setString(1, i);
getChatId.setString(2, friend);
ResultSet rss = getChatId.executeQuery();
while (rss.next()) {
PreparedStatement chat = conn.prepareStatement("CREATE TABLE " + rss.getInt("id") + "chat (username text NOT NULL, created_at timestamp with time zone NOT NULL DEFAULT now(), avatar text NOT NULL, message text NOT NULL, id serial NOT NULL);");
chat.execute(); //ERROR
return "done";
}
return "wat";
}

最佳答案

您看到的错误可能来自那里:

preparedStatement chat = conn.prepareStatement("CREATE TABLE " + rss.getInt("id") + "chat (...);");

通常在 SQL 中,表名不能以数字开头。如果您要用双引号将表名引起来,Postgres 仍然允许这样做,但是每次查询时都需要双引号表名,这可能会很乏味。

一种解决方案是将数字放在表名称的末尾,例如:

preparedStatement chat = conn.prepareStatement("CREATE TABLE chat" + rss.getInt("id") + " (...);");

<强> Demo on DB Fiddle :

create table 7chat(x int);
ERROR:  syntax error at or near "7"LINE 1: create table 7chat(x int);                     ^
create table "7chat"(x int);
-- works

create table chat7(x int);
--works

关于java - org.postgresql.util.PSQLException : ERROR: syntax error at or near "7",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57990640/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com