我正在尝试创建一个在数据库上运行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()返回一个布尔值,以说明是否返回了结果或是否有更多结果要返回。
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?
}