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
Related
I've been trying everything, nothing is working, I'm new to mysql and databases and I want to get the last auto-incremented id (primary key) (user_id) from a table, from java. So this: SELECT MAX(user_id) FROM database_user; works fine in mysql, I got that, but why can't I get the same thing from java??
PreparedStatement st = connection.prepareStatement("SELECT MAX(user_id) from database_user");
st.executeUpdate();
ResultSet rs = st.executeQuery();
int uid = rs.getInt(1);
System.out.println(uid);
This gives me java.sql.SQLException: (conn=213) the given SQL statement produces an unexpected ResultSet object
This isn't the only thing I tried, it's just the last one so far. If anyone could just shed some light I would greatly appreaciate it.
You are missing rs.next(); between executing the query and fetching from the result set. This is needed, to move the result set to the first row.
You also shouldn't have st.executeUpdate(). Just executing once is enough.
I am creating a new register in table MY_TABLE using java and then, I am doing a query to obtain the max(id) of that table. However, Java is obtaining the previous one. I mean:
mybean.store(con)
con.commit();
pstm = con.prepareStatement("SELECT MAX (ID) FROM MY_TABLE");
rs = pstm.executeQuery();
while (rs.next()){
id = rs.getString("ID");
System.out.println("id: " +id);
}
Before con.commit(); the table has the max(ID)=3
After com.commit() the table has the max(ID)=4
But I obtain MAX(ID)=3
Can somebody help me to solve this?
You're doing it; if this is returning the wrong result either your DB doesn't contain what you think it contains, or your DB engine is broken (MySQL is often broken, possibly that's the problem. The fix is to not use mysql), or your code is broken. Your snippet contains an error (no semicolon after the first line), so this isn't a straight paste but a modification; generally you should paste precisely the code that is exhibiting the behaviour you don't understand, because if you edit it or try to simplify it without running the simplification, you may have accidentally removed the very thing that would explain what you're observing.
More generally, if all you want is the ID generated for an auto-increment column, this isn't how you do it. You can use statement's .getGeneratedKeys() method to get at these; you may have to pass in Statement.RETURN_GENERATED_KEYS as part of your executeUpdate call.
You do not need a PreparedStatement if you do not have a parametrized query. I would use Statement in this case.
You do not need while (rs.next()) as your query will return a single value. I would use if (rs.next()).
Your query does not have a field called ID and therefore rs.getString("ID") will throw SQLException. You should use rs.getString(1) or use an alias (e.g. maxId in the example shown below) in the query. Also, you should use getInt instead of getString.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(ID) AS maxId FROM MY_TABLE");
int id = Integer.MIN_VALUE;
if (rs.next()) {
id = rs.getInt(1);
//id = rs.getInt("maxId");
}
System.out.println(id);
I want to export huge data from oracle to csv file. so i used simple JDBC select statement to get data in memory but and then write it to file, But data is very large of i am getting Out of memory exception. So i thought of using CallableStatement to call Stored Procedure which will return CURSOR with ResultSet as below :-
String getDBTableCursorSql = "{call getDBTableCursor(?,?)}";
callableStatement = dbConnection.prepareCall(getDBTableCursorSql);
callableStatement.setString(1, "test");
callableStatement.registerOutParameter(2, OracleTypes.CURSOR);
// execute getDBTableCursorSqlstore procedure
callableStatement.executeUpdate();
// get cursor and cast it to ResultSet
rs = (ResultSet) callableStatement.getObject(2);
// loop it like normal
while (rs.next()) {
String userid = rs.getString("ID");
String userName = rs.getString("NAME");
..
..
}
Oracle Proc :-
CREATE OR REPLACE PROCEDURE getDBTableCursor(
p_username IN DBUSER.USERNAME%TYPE,
c_dbuser OUT SYS_REFCURSOR)
IS
BEGIN
OPEN c_dbuser FOR
SELECT * FROM CUSTOMER WHERE USERNAME LIKE p_username || '%';
END;
Question 1 :-
does above ResultSet will fetch all the data in single shot ? or it will go to database for each rs.next(),
Question 2:-
is there any other approach which can deal with large data export to file in java using chunks so it wont get Out of memory issue?
I can't use pagination in this condition because of requirement.
Regarding your first question: the Oracle jdbc driver by default fetches 10 rows at a time. This can be verified or set to other value via standard jdbc:
https://docs.oracle.com/cd/E11882_01/java.112/e16548/resltset.htm#JJDBC28621
I have a stored procedure which creates a temp table and populates the temp table. After populating it, it returns the rows inside the table with (SELECT).
When running it from MySQL workbench works tremendously but in JAVA with JDBC, the ResultSet is empty. I have gone through some posts which say that we should not use PreparedStatment but even Statement doesn't work.
For test, I divided the job in stored procedure. Now I call:
CallableStatement ps = connection.prepareCall("{CALL myProcedure(?)}");
ps.setString(1, "value");
ps.execute();
which creates the temp table and populates it. Thereafter with same connection I try to do
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM tmp_table");
Still ResultSet is empty. What can I do? Any help is appreciated.
Thank you folks for help!
I found the error. The error was in code.
I send a parameter when calling procedure. For testing purposes I did
SET #param = "value";
Later on, I removed it but I forgot to remove it when inserting data into temporary table which used that #param. MySQL somehow could see that #param and IN param is same because of name but JDBC could not see that and Therefore, it was not returning any data.
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