我尝试用 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);
}
}
}
这里是异常(exception)
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 - 带有Java的Postgres我无法插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12866326/