Postgres with Java我无法插入数据
作者:互联网
我试图用Java插入我的postgres数据库.我有本地数据库的默认配置.
我想把一些数据放在一个表中,我有一些问题.
这是代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public static void main(String[] args) {
Connection con = null;
PreparedStatement pst = null;
String url = "jdbc:postgresql://localhost/postgres";
String user = "postgres";
String password = "thanassis";
try {
con = DriverManager.getConnection(url, user, password);
String stm = "INSERT INTO TEST2(ID) VALUES(?)";
pst = con.prepareStatement(stm);
pst.setInt(1, 1);
pst.executeUpdate();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(PreparedStatement.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(PreparedStatement.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
}
}
这里有例外
SEVERE: ERROR: relation "test2" does not exist Position: 13 org.postgresql.util.PSQLException: ERROR: relation "test2" does not exist Position: 13 at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2101) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1834) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:510) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:386) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:332) at test.Test.main(Test.java:30)
解决方法:
您的表名为TEST2而不是test2.显然,您使用双引号创建它,这使得Postgres(和其他符合标准的DBMS)区分大小写.
因此,每次引用时,您现在必须用双引号将表括起来.
String stm = "INSERT INTO \"TEST2\"(ID) VALUES(?)";
很可能这不是你想要的,所以只需重新创建表而不使用标识符周围的双引号:
CREATE TABLE test2
(
...
)
创建一个不同的表:
CREATE TABLE "test2"
(
...
)
如果您不想重新创建表,可以重命名它们:
alter table "TEST2" rename to test2;
标签:java,postgresql,sql-insert,quoted-identifier 来源: https://codeday.me/bug/20190901/1785094.html