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.
Related
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 have updated one of my tables to include the column canttouchthis using the MySQL Workbench.
From the MySQL Workbench there is no problem writing sql against the column canttouchthis. But, in my code I get the following error on any instance of said column, but the remained of the columns work just fine, such as groups.id
Unknown column 'groups.canttouchthis' in 'field list'
Even a simple select statement like the following doesn't work:
try {
String sql = "SELECT groups.canttouchthis FROM groups";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
data.addProperty("got_data", rs.getLong(groups.canttouchthis));
}
} catch (SQLException ex) {
StackTrace.print(ex);
}
I have tried reseting my Java Servlet Container server to no avail
I realized that I was passing the wrong database connection to this point.
Thanks for your vigilance, I would delete this question if I could.
You can create new alias like SELECT gp.canttouchthis AS ctt FROM groups as gp after user "ctt" in while loop
I want to insert some data into RDBMS(MYSQL5.7, JDBC5.1), and I am using executeBatch to speed up. I found that when one insert sql of a batch of statement cannot execute properly, the remain will be ignored. I have to say that not what I expectd. I want to let RDBMS just ignore my error sql and continue execution.
Can anyone tell me what should I do or show me the right documentation url.
And I am glad for your help!
And I know that "INSERT ... ON DUPLICATE KEY ... " can help ignore DUPLICATE KEY error , but I want one more general solution.
MySQL JDBC DOC
Connection connection = getConn();
Statement statemenet = connection.createStatement();
for (SearchUserItem user: result.getItems()) {
String query = "INSERT INTO TABLE VALUES(SOME_VALUES)";
}
int[] re = statemenet.executeBatch();
ananlyseBatchResult(re);
statemenet.close();
connection.close();
I have a java servlet application and I'm using a prepared query to update a record in a SQL Server Database table.
Lets say I want to execute UPDATE MyTable SET name = 'test' WHERE id = '10'. (Yes, id is a varchar)
I used the following code to make this happen:
PreparedStatement pstmt = con.prepareStatement("UPDATE MyTable SET name = ? WHERE id = ?");
pstmt.setString(1, getName() );
pstmt.setString(2, getID() );
pstmt.executeUpdate();
I found out that while I was running a JMeter script to simulate 2 users, this statement causes a deadlock in my database.
I wanted to check what my values were in the SQL Profiler so I used the following code, so I could check the values.
String query = String.format("UPDATE MyTable SET name = '%s' WHERE id = '%s' ", getName(), getID() );
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.executeUpdate();
Suddenly my deadlock was gone! It's a shame the last approach is vulnerable to SQL injection.
Is there somebody who can tell me what is going on and/or how to fix it?
Ok I finally found the problem and solution to my problem.
It seemed that the combination of the jTDS JDBC driver with MSSQL was the 'problem'.
This article explained my situation exactly. And with the help of this FAQ I was able to set the datasource to the right configuration.
From what I understand:
If you have statement that uses a String-like index (Like in my situation), the table performs an index SCAN instead of an index SEEK. This causes the whole table to be locked and vulnerable to deadlocks.
I hope this will help other people too.
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.