我是否在 PreparedStatement 中错误地使用了语法?
执行时:
1 statement = conn.prepareStatement("insert into ?.? (?) values(?)");
2 statement.setString(1, schemaName);
3 statement.setString(2, tableName);
4 statement.setString(3, columnName);
5 statement.setString(4, columnValue);
6 statement.executeUpdate();
7 conn.commit();
引发的异常:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2190)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:136)
at PostgreSQLDatabase.updateTable(MyClass.java:6)
答案 0 :(得分:3)
标识符(例如表名和列名)不能与占位符一起使用,因此您必须使用字符串操作,并且只使用values(?)
的占位符:
statement = conn.prepareStatement("insert into " + schemaName + "." + tableName + " (" + columnName + ") values(?)");
statement.setString(1, columnValue);
这假定您已选择schemaName
,tableName
和columnName
,以便它们不区分大小写或包含空格或类似的怪异。如果标识符区分大小写或包含空格等,那么您需要在SQL中对它们进行双引号:
"insert into \"" + schemaName + "\".\"" + ...
如果标识符也可以包含双引号,那么在将它们放入SQL之前,您必须将它们加倍。
该错误涉及$1
因为PostgreSQL本身使用编号占位符($1
,$2
,...)而JDBC正在将?
占位符转换为内部编号的占位符
答案 1 :(得分:-1)
试试这个
statement = conn.prepareStatement("insert into " + schemaName + ".? (?) values(?)");
statement.setString(1, tableName);
statement.setString(2, columnName);
statement.setString(3, columnValue);
statement.executeUpdate();
conn.commit();