This question already has answers here:
Cannot issue data manipulation statements with executeQuery()
(11 answers)
Closed 7 years ago.
I use com.mysql.jdbc.Driver
I need insert and get id.
My query:
INSERT INTO Sessions(id_user) VALUES(1);
SELECT LAST_INSERT_ID() FROM Sessions LIMIT 1;
error -
Can not issue data manipulation
statements with executeQuery()
How insert and get id?
You will need to use the executeUpdate() method to execute the INSERT statement, while you'll need to use the executeQuery() method to execute the SELECT statement. This is due to the requirements imposed by the JDBC specification on their usages:
From the Java API documentation for Statement.executeQuery():
Executes the given SQL statement, which returns a single ResultSet
object.
Parameters:
sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
and from the Java API documentation for Statement.executeUpdate():
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Parameters:
sql - an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
Your code (pseudo-code posted here) should appear as:
statement.executeUpdate("INSERT INTO Sessions(id_user) VALUES(1)"); // DML operation
statement.executeQuery("SELECT LAST_INSERT_ID()"); // SELECT operation
And of course, the MySQL documentation demonstrates how to perform the same activity for AUTO_INCREMENT columns, which is apparently what you need.
If you need to execute both of them together in the same transaction, by submitting the statements in one string with a semi-colon separating them like the following:
statement.execute("INSERT INTO Sessions(id_user) VALUES(1); SELECT LAST_INSERT_ID() FROM Sessions LIMIT 1;");
then you'll need to use the execute() method. Note, that this depends on the support offered by the Database and the JDBC driver for batching statements together in a single execute(). This is supported in Sybase and MSSQL Server, but I do not think it is supported in MySQL.
may be you are using executeQuery() but to manipulate data you actually need executeUpdate() rather than executeQuery()
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet generatedKeys = null;
try {
connection = m_Connection;
preparedStatement = (PreparedStatement) connection.prepareStatement(qString, Statement.RETURN_GENERATED_KEYS);
// ...
int affectedRows = preparedStatement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
generatedKeys = preparedStatement.getGeneratedKeys();
int id = -1;
if (generatedKeys.next()) {
id = generatedKeys.getInt(1);
id = -1;
} else {
throw new SQLException("Creating user failed, no generated key obtained.");
}
} finally {
}
For non-select SQL statements you use ExecuteNonQuery();
To get the last inserted id, you can do this SQL statement.
SELECT LAST_INSERT_ID() AS last_id
Although there's probably an java wrapper for that select statement.
Links:
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://wiki.bibalex.org/JavaDoc/org/bibalex/daf/handlers/dbhandler/DBConnection.html
Related
I am trying to connect DB2 via JDBC. How do I get the output message that sql would have returned as like IDE.
E.g Select query would return 100 rows were fetched.
Insert would return the number of rows updated.
Also the error messages like no rows found, User does not have privilege to access database, Insert could not be performed due to duplicate primary key etc.
catch the exception thrown and print the stack trace.
try{
// your SQL work
} catch(Exception e){
e.printStackTrace();
}
This will print the error in your output console.
Use the JDBC api execute update to get the changed row count. And the exceptions to get other messages.
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
int executeUpdate(String sql) throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or
DELETE statement or an SQL statement that returns nothing, such as an
SQL DDL statement. Note:This method cannot be called on a
PreparedStatement or CallableStatement.
Parameters: sql - an SQL Data Manipulation Language (DML) statement,
such as INSERT, UPDATE or DELETE; or an SQL statement that returns
nothing, such as a DDL statement.
Returns: either the row count
for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL
statements that return nothing
Throws: SQLException - if a database
access error occurs, this method is called on a closed Statement, the
given SQL statement produces a ResultSet object, 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
I am trying to insert into a db that I have, and I'd like to do so through parameters. I am connecting to a postgres db using java.
I can connect to the db just fine. I know that because I have various operations that I am using that are already working were I can see, and update existing rows in my db. I am having trouble with INSERT.
I have the following:
private String _update_rentals = "INSERT into rentals (cid, mid) values (?,?)";
private PreparedStatement _update_rentals_statement;
private String _update_movie_status = "UPDATE Movie SET checkedout = true WHERE mid = ?";
private PreparedStatement _update_movie_status_statement;
And I initialize them:
_update_movie_status_statement = _customer_db.prepareStatement(_update_movie_status);
_update_rentals_statement = _customer_db.prepareStatement(_update_rentals);
And
while (movieAvail.next()){
System.out.println(movieAvail.getBoolean(1));
if (movieAvail.getBoolean(1) == false){
//Do chekcout
_update_rentals_statement.clearParameters();
_update_rentals_statement.setInt(1, cid);
_update_rentals_statement.setInt(2, mid);
_update_rentals_statement.executeQuery();
_update_movie_status_statement.clearParameters();
_update_movie_status_statement.setInt(1, mid);
_update_movie_status_statement.executeQuery();
System.out.println("Enjoy your movie!");
}
}
I am getting an error with both of the executeQuery() calls. For some reason I am getting the following error with both:
Exception in thread "main" org.postgresql.util.PSQLException: No results were returned by the query.
I looked at other posts, and I believed that I was following syntax for both insert/ update correctly, so maybe I am overlooking some aspect of this.
This is all part of a larger code base, so I did not want to include the methods these pieces of code are in. But these are the isolated instances which play a part with this code.
In general, when you execute a query, you are willing to retrieve some kind of information from the database. This is usually the case when you are executing SELECT queries. However, with INSERT and UPDATE statements, you are not querying the database, you are simply executing an update or inserting new rows. In the documentation of PreparedStatement you can see in which cases an exception is being thrown when you try to call executeQuery:
Throws: SQLException - if a database access error occurs; this method
is called on a closed PreparedStatement or the SQL statement does not
return a ResultSet object
So in your case the problem is that your statements do not return a ResultSet. You should use execute or executeUpdate instead. The former simply executes the update, while the latter does the same, but also returns the number of affected rows.
I think the main issue is that you are calling executeQuery(), which expects a result to be returned, but Insert/Update are not queries and don't return a result. Try just calling execute().
I am inserting data to a MySQL DB, but get an error, when executing the insert statement:
The ResultSet can not be null for Statement.executeQuery.
Although if i check the database table, I find that the values have been successfully inserted. This is confusing.
Code Snippet
Connection connection = null;
connection = DriverManager.getConnection("jdbc:google:rdbms://name-of-instance");
Statement check = connection.createStatement();
java.sql.ResultSet resultset = null;
resultset = check.executeQuery("insert into table_name values (values-inserted-here);");
To execute queries that update, delete or insert any data in your DB, you cannot use executeQuery(String sql) (check here the docs), but executeUpdate(String sql) instead.
So instead of:
check.executeQuery("insert into table_name values (values-inserted-here);");
You should do:
check.executeUpdate("insert into table_name values (values-inserted-here);");
The ResultSet is always null in an insert, delete or update, that is why it was giving you that error. If you use executeUpdate the error should be gone.
Hope it helps!
No need to use ResultSet.
ResultSet only used when you fetch data from query like select query.
Just use
Statement check = connection.createStatement();
check.executeUpdate("insert into table_name values (values-inserted-here)");
and for tutorial use this link
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?
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.
If you're performing an INSERT/UPDATE statement, you should be calling stmt.executeUpdate() rather than stmt.executeQuery(). I imagine there's a difference (though I don't know exactly what) between the Oracle and SQL Server drivers you're using that means that one works and the other one doesn't.
try using the method executeUpdate instead of executeQuery.
since the query at hand is not a select-query, it fails. executeQuery is for select-queries, executeUpdate is for insert, delete and update-queries.
There is the problem on stmt.executeQuery();
executeQuery() is used for SELECT sql operation
executeUpdate() is used for INSERT, UPDATE and DELETE sql operation.
your query is for INSERT operation thus please use stmt.executeUpdate();
This depends upon driver that are using and underlying implementation of executeQuery() method. While using Java Prepared statement the underlying implementation allow this but the driver of SQL server doesnot allow this.
Try to use correct method to execute insert statement like executeUpdate().
go trough this links:-
Sql server:- http://msdn.microsoft.com/en-us/library/ms378540%28v=sql.90%29.aspx
Oracle:- http://docs.oracle.com/javase/1.4.2/docs/guide/jdbc/getstart/statement.html
use stmt.execute(); instead of stmt.executeQuery();
stmt.execute(); or executeUpdate(); for INSERT, UPDATE, DELETE (etc.)
stmt.executeQuery(); for SELECT
I'm having issues with stored procedures that have a lot of insert statements when using Sybase's jdbc driver. After 50-60 inserts, the stored procedure stops execution and returns. See code below.
I'm using Sybase Anywhere 10 and their jconn2.jar, but have also tried jconn3.jar.
java code:
String sp = "sp_test";
Statement stmt = con.createStatement();
stmt.execute(sp);
stmt.close();
stored procedure:
create procedure dba.sp_test()
as
begin
declare #lnCount integer
select #lnCount = 1
while (#lnCount <= 1000 )
begin
insert into tableTest (pk) values (#lnCount)
select #lnCount = #lnCount + 1
end
end
After 58 inserts the procedure returns. Doing a select count(*) from tableTest afterward returns a count of 58. There are not SQLExceptions being thrown. I tried putting a begin/commit transaction around the insert, but it didn't make a difference. I've also tried the jodbc driver and it works fine, but I'm not able to use this as a solution because I've had other issues with it.
Using executeUpdate solved the problem:
String sp = "sp_test";
Statement stmt = con.createStatement();
stmt.executeUpdate(sp);
stmt.close();
I believe if you insert con.commit() immediately after stmt.execute() would work too.