Resultset closed exception - java

I am trying to retrieve results from a DB in a resultset. However i want to execute an update query for each entry in the resultset, but i get an exception.
this is my code
try {
Statement statement = sqlconnection.conn.createStatement();
query = "select * from reminders where year<= "+ syear +" and month<=" + smonth +" and date<"+ sday +" and reminded like 'false';";
rs= statement.executeQuery(query);
while (rs.next()){
id=rs.getInt("sno");
String reminder = rs.getString("remind");
JOptionPane.showMessageDialog(null, reminder);
statement.executeUpdate("update reminders set reminded='true' where sno="+id+";");
}
Can any1 show me a better way of doing this ?? I am pretty new to programming. Hence showing me how to it will be really helpful.
thanks

You're still looping over the results from statement when you're trying to perform an update with it. I'd try using a second Statement object for your updates.

Your ResultSet is not updatable.
Statement statement = sqlconnection.conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

Related

How to use textfield input in mysql SELECT query

I am using Java netbeans and mysql. I want to check whether the value entered by the user in a textfield tf is already present in the mysql table or not.
String query1="SELECT * FROM trytable WHERE name='8'";
ResultSet rs=stmt.executeQuery(query1);
if(rs.isBeforeFirst()==true){JOptionPane.showMessageDialog(null,"already");}
In the above code in place of 8 I want to give the value that the user input in the form and then check whether that value already exist in form or not.
Please help me in the first line . Thanks
You should use a PreparedStatement instead of a regular statement. This is more secure than a normal Statement and allows you to avoid SQL injection issues.
You would change your query like so:
String query = "SELECT * FROM trytable WHERE name='?';";
Note the ? at the end of the query. This can be replaced later in your code when setting up the PreparedStatement:
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, userInput);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) System.out.println("Record exists!");
Here, you are telling the prepared statement to replace the first ? in the query, with the value of userInput. So, if the user inputs a 3, the query that gets executed would be SELECT * FROM trytable WHERE name=3;.
Also note that rs.next() returns true if the query returns any results, so that would be the proper way to determine if the record exists.
ResultSet is like a table, it has a cursor. At the beginning the cursor is above the first row so isBeforeFirst() will always return true even there are no results in the ResultSet.
In order to retrieve results you need to move the cursor to the next row, to do that you can use,
rs.next()
If the cursor moved to the next row successfully (which means there are more results) it will return true otherwise false. As you only need the first result you can also use,
rs.first()
to confirm there are data available in the returned ResultSet.
Try,
if (rs.first()) {
JOptionPane.showMessageDialog(null, "already");
}
This is the final code will is working absolutely fine.
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","");
String query = "SELECT * FROM table_name WHERE name=?;";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,jtf.getText());
ResultSet rs = preparedStatement.executeQuery();
if(rs.next()==true){
JOptionPane.showMessageDialog(null,"Value already exist");
}
else{
JOptionPane.showMessageDialog(null,"Value not present");
String query1="INSERT INTO table_name(col_name) VALUES (?)";
preparedStatement = conn.prepareStatement(query1);
preparedStatement.setString(1,jtf.getText());
preparedStatement.execute();
JOptionPane.showMessageDialog(null,"DONE");
}
rs.close();
preparedStatement.close();
}
catch(Exception e){
System.out.println("Exception:"+e.getMessage());
}

Can you help me to find the error below in the ResultSet rs=stmt....? [duplicate]

This question already has an answer here:
ResultSet is not for INSERT query? Error message: Type mismatch: cannot convert from int to String
(1 answer)
Closed 5 years ago.
I am getting a error on the resultset rs part where netbeans shows the error as
incompatible types:int cannot be converted to resultset
Class.forName("java.sql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?useSSL=false", "root", "abc");
Statement stmt = conn.createStatement();
String query = "SELECT * FROM patient WHERE Mobile_No='" + mobno + "';"; /*Get the value from the database*/
ResultSet rs = stmt.executeUpdate(query);/*Part where the error is appearing*/
while (rs.next()) {
String Name = rs.getString("Name");
String Age = rs.getString("Age");
String Mobile = rs.getString("Mobile_No");
String gender = rs.getString("Gender");
String symptoms = rs.getString("Symptoms");
model.addRow(new Object[]{Name, Age, Mobile, gender, symptoms});
}
rs.close();
stmt.close();
conn.close();
Use stmt.executeQuery(String sql), it returns ResultSet.
If you want a ResultSet returned you should use executeQuery, not executeUpdate.
The stmt.executeUpdate(query); doesn't fit for an SELECT query.
You need to replace it by stmt.executeQuery(query);
Well the method executeUpdate returns a int not a results set, seen in the documentation here: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
the integer being return being either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
the method you are actually want to use is executeQuery and the documentation for that can be found at:
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)
According the Javadoc (https://docs.oracle.com/javase/9/docs/api/java/sql/Statement.html#executeUpdate-java.lang.String-), stmt.executeUpdate(query); returns an int and not a ResultSet object.
From the Javadoc :
Returns:
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
I think you must use stmt.executeQuery(query); instead, which return the ResultSet you expect. You're doing a SELECT and not an INSERT, UPDATE, or DELETE operation.
I believe people have already answered your question, which is statement.executeUpdate(query) returns the number of how many rows has been affected by executing the query, and you should use statement.executeQuery(query) instead ..
But this part String query = "SELECT * FROM patient WHERE Mobile_No = '" + mobno + "';" is very bad approach, it will leave the door opened for SQL injection, you should use PreparedStatement instead of Statement

How to assign a Value taken from the database to a label?

I need to assign a string taken by a query from the database to a Jlabel. I tried many methods but failed. How can i do it?
try{
String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' ";
pst=conn.prepareStatement(sql);
String x= (pst.execute());
}
catch(Exception e){
}
Need to study the steps to connect to the database in java First db steps
Get the resultset from the statment by calling ResultSet rs = pst.execute();
Iterate through the list of rows by using the resultset object.
After that assign the value to the JLabel.
You just made several errors in your tiny program, take a look at the code below as an example:
// your way of using prepared statement is wrong.
// use like this
String sql="SELECT MAX(allocationID) FROM allocation where unit=?;";
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
// assign values to the variables in the query string
ps.setString(1, dept);
// execute the query
ResultSet rst = ps.executeQuery();
// parse the result set to get the value
// You'd better do some check here to ensure you get the right result
rst.next();
String x = rst.getInt(1) + "";
ps.close();
conn.close();
}
Have a look at the article if you are interested:https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html

SQLite select from LIKE statement not working?

When I view the database and run this query I get results as expected.
SELECT * FROM users WHERE options LIKE '%[-15,-3]%';
However when I use a prepared statement as seen below, the uuid is null.
String opt = "[-15,-3]"; //example
PreparedStatement ps = SQLite.connection.prepareStatement(
"SELECT * FROM users WHERE options LIKE '%" + opt + "%'"
);
ResultSet rs = ps.executeQuery();
String uuid = null;
while (rs.next()){
uuid = rs.getString("member");
}
rs.close();
ps.close();
if(uuid != null){
System.out.println("not null: " + uuid);
return Database.getUser(UUID.fromString(uuid);
}
For the code above, nothing is returned in the result set. Which is very strange because I used the same query with an SQLite viewer and it returned the proper rows. How can I solve this? I don't see an issue.
UPDATE
When I directly use "SELECT * FROM factions WHERE claims LIKE '%[-15,-3]%'" in the prepared statement instead of the variable, it works fine. Why can't I use a string variable? I've checked the variable and it prints to console fine.
I solved it after a lot of trial and error, turns out I should've been using a ? and set the string.
PreparedStatement ps = SQLite.connection.prepareStatement(
"SELECT * FROM users WHERE options LIKE ?"
);
ps.setString(1, "%" + opt + "%");

Updating database after updating resultset

I have the below code to get data from a database and update it. How ever, result set is getting updated but, I don't see the changes in the database. Even after I say commit(), database is not getting updated. What am I missing here?
Connection connect = ConnectionManager.getInstance().getConnection();
Statement st = connect.createStatement();
st.execute("Select * from ...");
ResultSet rs = st.getResultSet();
ResultSetMetaData md = rs.getMetaData() ;
rs.absolute(1);
rs.updateObject("StepName","ABCD" );
connect.commit();
//connect.close();
EDIT:
Now, i have the below method, but I get the error as indicated.
rs.updateString("StepName", "ABCD");
rs.updateRow();
//rs.updateObject("StepName","ABCD" );
Error: com.jnetdirect.jsql.u: sp_cursor: The cursor identifier value provided (0) is not valid.
OK I have it working now. Below is the way I had to change.
Working solution:
Connection connect = ConnectionManager.getInstance().getConnection();
Statement st = connect.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
st.execute("Select * from ...");
ResultSet rs = st.getResultSet();
String queuename = "apples";
String updatedname = "bananas";
while(rs.next())
{
if(rs.getString(3).equals(queuename))
{
rs.updateString(3, updatedname );
System.out.println("updated: " + rs.getString(3));
rs.updateRow();
}else
{
System.out.println(rs.getRow() + ": " + rs.getString(3));
}
}
connect.commit();
rs.close();
connect.close();
}
If you look at the spec of updateObject :
Updates the designated column with an Object value. The updater methods are used to update column values in the current row or the insert row. The updater methods do not update the underlying database; instead the updateRow or insertRow methods are called to update the database.
rs.updateObject alone doesn't update the database. Try adding a call to rs.updateRow() after updateObject.
rs.absolute(1); might be not be moving the cursor. Try:
rs.next();
You can try a straight up SQL statement:
StringBuffer updates = new StringBuffer();
updates.append("UPDATE table_name ");
updates.append("SET StepName = ? );
updates.append("WHERE id = ?");
Statement updateStatement = connect.createStatement(updates.toString());
updateStatement.setString(1, "BlaBla");
updateStatement.setInt(2, 143);
updateStatement.executeUpdate();
When you make your call to createStatement you need to use the overload that allows you to specify an updatable resultset.
Here is an example if found: http://www.xyzws.com/Javafaq/how-to-use-updatable-resultset-in-jdbc/179
I think it's possible that not all driver\databases support this operation.

Categories

Resources