日期:2014-05-16  浏览次数:20380 次

PreparedStatement的excute返回值的让我疑惑

? 今天用jdbc写了一句sql语句,通过PreparedStatement对象来插入记录,发现一个奇怪的问题,我明明是成功插入记录,可是pstmt.execute()确返回的是false,狂晕中。

String sqlText = "insert into problem(title, " +
		"description, input, output, sample_input, " +
		"sample_output, hint, source, uploader) " +
		"values(?, ?, ?, ?, ?, ?, ?, ?, ?)";
	PreparedStatement pstmt = null;
......
res = pstmt.execute();

?

??? 呵呵,感到比较困惑。查看sun的API后恍然大悟。

sun API 写道
public boolean execute()
throws SQLExceptionExecutes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement. Some prepared statements return multiple results; the execute method handles these complex statements as well as the simpler form of statements handled by the methods executeQuery and executeUpdate.
The execute method returns a boolean to indicate the form of the first result. You must call either the method getResultSet or getUpdateCount to retrieve the result; you must call getMoreResults to move to any subsequent result(s).


Returns:
true if the first result is a ResultSet object; false if the first result is an update count or there is no result
Throws:
SQLException - if a database access error occurs or an argument is supplied to this method

???? 再次发现一个小问题,我将如何判断这条记录是否插入成功呢?我选择了不用execut方法,而改用executeUpdate方法。

if(pstmt.executeUpdate() == 1)
	return true;
else
	return false;

???? executeUpdate()返回数据库中更新记录的条数。那哪位大侠出来说一下execute该在什么情况下使用哇?

1 楼 抛出异常的爱 2010-05-10  
在执行此PreparedStatement对象的SQL语句,
它可以是任何类型的SQL语句。
一些准备语句返回多个结果;
execute方法处理这些复杂的报表,
以及简单的executeQuery和executeUpdate方法构成语句处理的。
执行方法返回一个布尔值来表示结果的形式第一次。
您必须调用方法getResultSet或者getUpdateCount来检索结果,
你必须调用getMoreResults移动到以后的任何结果

google 翻译器