Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

java - Inserting preparedstatement to database - PSQL

This seems like a really simple problem, but I cannot figure out what my problem is. I have a method addTask which adds some info to our database as seen in this code:

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;
      }
}

my problem is that preparedStatement.execute() always returns false, indicating the information hasnt been added to the database. I can run psql and this confirms that nothing has been written to the db. The connection definitely connects to the correct database (i put in some other printlns etc. to check this). I am trying to insert into a newly initialised table that looks like this:

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
); 

code for 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;
}

where USER and PASSWORD are static fields in the class

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You misunderstood the return value of PreparedStatement#execute().

Please carefully read the javadoc:

Returns:

true if the first result is a ResultSet object; false if the first result is an update count or there is no result.

It thus returns — as fully expected — false on an INSERT query. It returns only true on a SELECT query (for which you'd however usually like to use executeQuery() instead which returns directly a ResultSet).

If you're interested in the affected rows, rather use PreparedStatement#executeUpdate() instead. It returns an int as per the javadoc:

Returns:

either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

A return value of 1 or greater would then indicate a successful insert.


Unrelated to the concrete problem: your code is leaking DB resources. Please carefully read How often should Connection, Statement and ResultSet be closed in JDBC?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...