如何在 Java 语句中使用 execute() 获取 true 或 false

how to get true or false using execute() in Java Statement

我有 Statement 对象 stmt,Connection 对象 conn.

stmt = conn.createStatement();
boolean b = stmt.execute("INSERT INTO employee VALUES('E001', 'Smith')")

但这总是会产生 false。如果上述查询成功执行,我想要 true,如果查询执行失败,我想要 false。我如何使用 execute() 方法获得该结果。

如果不是 select 查询,则不能。
这是文档中所说的

Returns:  
true if the first result is a ResultSet object; false if it is an update count or there are no results`.

当你给出一个 select 查询而不是插入或更新时,你会得到一个结果集,在这些类型的查询中你总是会得到 false 。
现在要确定它 运行 是否成功,我想使用 e Exceptions 会帮助你

使用 executeUpdate() 会给你行数,这样你就可以用它来预测。

你正在做一个插入语句,如果有一个结果集有从执行语句返回的值,就会有一个结果。 Check the documentation

尝试在 Statement 上使用 executeUpdate() 方法。它应该 return 你一个指示行数的整数。

如果第一个结果是 ResultSet 对象,

Statement.ececute() 将 return 为真,如果是更新计数或没有结果则为假

您可以使用

int executeUpdate(String sql)

returns

1) the row count for SQL Data Manipulation Language (DML) statements or

2) 0 for SQL statements that return nothing

Docs

How can I achieve that result using execute() method.

你不能。如果结果有 ResultSet,它只会 return true。如果您的插入有问题,该方法将抛出异常。来自 documentation:

boolean execute(String sql) throws SQLException

Returns:

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

Throws:

SQLException - if a database access error occurs, this method is called on a closed Statement, the method is called on a PreparedStatement or CallableStatement

SQLTimeoutException - when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement