I know that to execute sql DELETE statement, I need to use executeUpdate(). However my need is to support only SELECT statment, hence I am using executeQuery(String sql). My db is Oracle.
My problem is, I am using java.sql.Statement.executeQuery(String sql) in a desktop based application, a textbox in our app accepts any kind of query and while testing we found that executeQuery(sql) is actually executing a DELETE query, ie it is successfully deleting a record and then throwing error -SQLException.
You will need to explicitely manage not execute INSERT, UPDATE & DELETE queries through executeQuery() method. This is as per the JDBC specification so it will accept delete queries as well and will throw an exception.
executeQuery() is used for SELECT sql operation
executeUpdate() is used for INSERT, UPDATE and DELETE sql operation.
your query is for DELETE operation thus please use stmt.executeUpdate();
As you mentioned the you are getting this from a textbox form user, You can add the validations on the query string itself before executing it.
Lets say you get the query in String, you can check if string starts with SELECT then only execute.
if (StringUtils.startsWithIgnoreCaseAndWs(sql, "INSERT")
|| StringUtils.startsWithIgnoreCaseAndWs(sql, "UPDATE")
|| StringUtils.startsWithIgnoreCaseAndWs(sql, "DELETE")
|| StringUtils.startsWithIgnoreCaseAndWs(sql, "DROP")
|| StringUtils.startsWithIgnoreCaseAndWs(sql, "CREATE")
|| StringUtils.startsWithIgnoreCaseAndWs(sql, "ALTER")
|| StringUtils.startsWithIgnoreCaseAndWs(sql, "TRUNCATE")) {
// Return message Unable to execute any update or modification queries through executeQuery()
} else {
//Execute Query
}
To prevent executeQuery
to be used in DELETE execution, use return types in your code. ie if and DML is there, then the return type should always be int.--
int i=stmt.executeUpdate('');
if you use int i=stmt.executeQuery(''); -- it will gives you compile time error
int i=stmt.executeQuery(''); -- it will gives you compile time error
And prevents you from using executeQuery
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.