Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement executing successfully in oracle but throwing exception in Microsoft SQL

I have this below query that I execute using java PreparedStatement:

String dml=insert into users(name, addr, city, sex, dob) values(?,?,?,?,?);
PreparedStatement stmt = conn.prepareStatement(dml);
stmt.setString(1,"abcd");
stmt.setString(2,"def");
stmt.setString(3,"ghij");
stmt.setString(4,"m");
stmt.setString(5,"1-Jan-1987");
stmt.executeQuery();

It executes successfully when the database is Oracle, but when the database is Microsoft SQL, then it throws an exception "java.sql.SQLException: The executeQuery method must return a result set". Could someone please tell what is the issue here. Why is the same query executing successfully in oracle but not in microsft sql?

like image 248
neeraj narang Avatar asked Dec 02 '22 00:12

neeraj narang


1 Answers

The answer is in the message - ExecuteQuery requires a result set. Use executeUpdate instead.

From the above Link:

  • boolean execute() Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.

  • ResultSet executeQuery() Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

  • int executeUpdate() Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.

the fact that it works on oracle is probably just a side effect which you've discovered cannot be relied upon.

like image 123
Preet Sangha Avatar answered Jan 01 '23 15:01

Preet Sangha