开发者

Beginner JDBC Result Set questions

开发者 https://www.devze.com 2023-01-13 16:24 出处:网络
New to using JDBC and I was wondering if all operations produce a result set. For example I am making statements to insert/update to a database via:

New to using JDBC and I was wondering if all operations produce a result set. For example I am making statements to insert/update to a database via:

StringBuffer query1 = new StringBuffer("UPDATE table SET col1 = value, WHERE some_col = some_val");
PreparedStatement pstmt1 = con.prepareStatment(query1.toString());
ResultSet rs1 = pstmt1.executeQuery();

So would this snippet, when executed just act out the appropriate update and be done? Or would I need to handle the开发者_开发问答 result set in some way in order to complete the operation?

Thanks for the help in advance.


You should be using PreparedStatement#executeUpdate() rather than executeQuery(). It returns an int indicating the amount of affected rows.

int affectedRows = preparedStatement.executeUpdate();

That said, constructing a SQL string that way is not the normal idiom. You would rather like to use placeholders ? and use the PreparedStatement setters to set the values.

String sql = "UPDATE table SET col1 = ? WHERE some_col = ?";
// ...    
preparedStatement = connection.prepareStatment(sql);
preparedStatement.setString(1, col1);
preparedStatement.setString(2, someCol);
int affectedRows = preparedStatement.executeUpdate();
// ...

See also:

  • Basic JDBC tutorial
  • Using PreparedStatement


No, you don't have to handle the ResultSet - it will be empty anyway, because an update operation shouldn't return results from the database. Usually you would call a different metho on the statement:

StringBuffer query1 = new StringBuffer("UPDATE table SET col1 = value, WHERE some_col = some_val");
PreparedStatement pstmt1 = con.prepareStatment(query1.toString());
int rowCount = pstmt1.executeUpdate();


tthere is another method for such statements:
s.execute("..");

0

精彩评论

暂无评论...
验证码 换一张
取 消