将preparedstatement插入数据库 - PSQL

ElF*_*Fik 0 java postgresql jdbc

这似乎是一个非常简单的问题,但我无法弄清楚我的问题是什么.我有一个方法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;
      }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是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
); 
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

where USERPASSWORD是类中的静态字段

Bal*_*usC 6

你误解了它的回报价值PreparedStatement#execute().

请仔细阅读javadoc:

返回:

true如果第一个结果是一个ResultSet对象; false如果第一个结果是更新计数或没有结果.

因此,它falseINSERT查询中返回 - 如完全预期的那样.它只返回true一个SELECT查询(但是你通常喜欢使用它executeQuery()而不是直接返回一个查询ResultSet).

如果您对受影响的行感兴趣,请PreparedStatement#executeUpdate()改用.它int按照javadoc返回:

返回:

(1)SQL数据操作语言(DML)语句的行数或(2)0表示不返回任何内容的SQL语句

返回值1或更大将表示成功插入.


具体问题无关:您的代码正在泄漏数据库资源.请仔细阅读在JDBC中关闭Connection,Statement和ResultSet的频率?