我正在尝试创建一个在数据库上运行 mySQL 查询/语句的工具。 我遇到的问题是这些查询/语句是自由格式的文本,例如文本框 - 我还将它们与专业的 SQL 程序一起使用。 举个例子,它会是这样的:
#Example of a query statement
@SET fName = "John"
SELECT * FROM Person WHERE Person.firstName = fName
#Example of an execute statement
@SET fName = "John"
DELETE FROM Person WHERE Person.firstName = fName
正如您所看到的,查询/语句可能包含注释、SET 语句,然后是执行语句或选择查询。此外,它们的格式可能并不总是正确,因此内容、制表符或空格之间可能存在空行。
我知道PreparedStatements 的选项,但是虽然这可以工作,但它并不真正符合整个查询/语句可作为自由格式文本进行编辑的要求。 我的问题是如何通过Java执行这些语句/查询? executeBatch 适用于第二个示例,但不适用于第一个示例,因为它返回 ResultSet。
最佳答案
解决方案是使用 Statement.execute() 而不是更具体的函数之一,如 .executeUpdate() 或 .executeQuery() 甚至 .executeBatch()
函数.execute()返回一个 boolean 值来表示是否有返回结果或者是否有更多结果需要获取。
public void executeAll(String queryString) throws SQLException {
boolean hasMoreResults = statement.execute(queryString);
int updateCount = statement.getUpdateCount();
while(hasMoreResults || (!hasMoreResults && updateCount != -1)){
//.execute() can be false if a query is not returned as when using a SET/ UPDATE/ DELETE which is why we check if updateCount is -1 meaning there are no more statements returned
if(hasMoreResults){
resultSet = statement.getResultSet();
//Do what you need to do with the ResultSet
} else {
//Else it's a UPDATE/ DELETE count - int
//Do what you need to do with the updateCount
}
hasMoreResults = statement.getMoreResults();
updateCount = statement.getUpdateCount();
//New values for the next cycle
}
//Possibly return stuff?
}
关于java - 将 SET 语句与普通语句组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36599450/