这似乎是一个非常简单的问题,但我无法弄清楚我的问题是什么。我有一个方法addTask,它将一些信息添加到我们的数据库中,如下面的代码所示:
public static boolean addTask(String name, String question, int accuracy, int type){
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO tasks (name, question, type, accuracy) ");
sql.append("VALUES(?, ?, ?, ?)");
try {
Connection c = DbAdaptor.connect();
PreparedStatement preparedStatement = c.prepareStatement(sql.toString());
preparedStatement.setString(1, name);
preparedStatement.setString(2, question);
preparedStatement.setInt(3, type);
preparedStatement.setInt(4, accuracy);
preparedStatement.execute();
preparedStatement.close();
c.close();
return true;
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
}
我的问题是preparedStatement.execute()总是返回false,表示信息尚未添加到数据库中。我可以运行psql,这确认没有任何内容写入数据库。连接肯定连接到正确的数据库(我放入一些其他printlns等来检查这个)。我试图插入一个新的初始化表,看起来像这样:
CREATE TABLE tasks
(
id SERIAL PRIMARY KEY,
submitter INTEGER REFERENCES accounts (id),
name VARCHAR(100) NOT NULL,
question VARCHAR(100) NOT NULL,
accuracy INTEGER NOT NULL,
type INTEGER REFERENCES types (id),
ex_time TIMESTAMP,
date_created TIMESTAMP
);
DbAdaptor.connect()的代码:
public static Connection connect(){
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PASSWORD);
try {
return DriverManager.getConnection(URL, properties);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
其中USER
和PASSWORD
是类
答案 0 :(得分:6)
您误解了PreparedStatement#execute()
的返回值。
请仔细阅读the javadoc:
返回:
true
如果第一个结果是ResultSet
个对象;false
如果第一个结果是更新计数或没有结果。
它在false
查询中返回 - 完全预期 - INSERT
。它只会在true
查询中返回SELECT
(但您通常希望使用executeQuery()
而不是直接返回ResultSet
)。
如果您对受影响的行感兴趣,请改用PreparedStatement#executeUpdate()
。它根据the javadoc返回int
:
返回:
(1)SQL数据操作语言(DML)语句的行数或(2)0表示不返回任何内容的SQL语句
返回值1或更大将表示插入成功。
无关具体问题:您的代码泄露了数据库资源。请仔细阅读How often should Connection, Statement and ResultSet be closed in JDBC?