how to fix "This ResultSet is closed " error? - java

I want to use two sql query in my java code. the first query retain all row of table2 and the second one get it's rows one by one. I wrote follow code but it face to "This ResultSet is closed, it means rs ResultSet " error. How can I fix?
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
ResultSet rsWithin = stmt.executeQuery(sqlWithin);
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}

You need to create separate PreparedStatement object for inner query
try{
String sqlSelectTable2 = "SELECT * FROM table2;";
ResultSet rs = stmt.executeQuery(sqlSelectTable2);
while (rs.next()) {
String strLineId = rs.getString(1);
String strPoints = rs.getString(2);
PreparedStatement preparedStatement = null;
String sqlWithin = "SELECT ST_Within(ST_GeometryFromText('POINT( ),ST_GeomFromText('POLYGON((443425 4427680, 441353 4427680, 441368 4426075, 443762 4426149, 443425 4427680))', 4326));";
preparedStatement = dbConnection.prepareStatement(sqlWithin);
ResultSet rsWithin = preparedStatement.executeQuery();
} // end while ... **It get error when it is reading second ResultSet **
} catch (Exception e) {
System.out.println(e.getMessage());
}

Related

ERREUR : Unknown column 'Accessoires' in 'where clause'

My query is throwing up this error while i have column Accessoires in table categorie Can anyone see why?
public int rechercheParCat(String test) {
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre="+test;
PreparedStatement pst = cnx2.prepareStatement(query);
ResultSet rs = pst.executeQuery(query);
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}
I FIXED IT LIKE THIS:
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre=? ";
PreparedStatement pst = cnx2.prepareStatement(query);
pst.setString(1, test);
ResultSet rs = pst.executeQuery();
rs.first();
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}```
Using bound parameters with a prepared statement likely fixes your bug and also solves the severe security issue.
public int rechercheParCat(String test) {
int idcat = 0;
try {
String query = "SELECT id_cat FROM categorie WHERE titre = ?";
PreparedStatement pst = cnx2.prepareStatement(query);
pst.setString(1, test);
ResultSet rs = pst.executeQuery(query);
idcat = rs.getInt(1);
} catch (SQLException ex) {
System.err.println(ex.getMessage());
}
return idcat;
}
The likely reason your code has failed is that test was "Accessoires", so the resulting SQL statement was:
SELECT id_cat FROM categorie WHERE titre=Accessoires
when in fact it should have been:
SELECT id_cat FROM categorie WHERE titre='Accessoires'
Even if you added quotes to the concatenated statement, you'd still have a problem. Just imagine what happens if somebody passes a value with quotes, e.g. O'Connor. This will just break the code. But a more clever person can inject SQL clauses.

How to combine 2 parameters in Prepared statement

I want to convert below java Statement into PreparedStatement combining 2 parameters i.e. input1 and input2. How to do that?
public static void main(String[] args) {
String input1="Hello";
String input2="World";
try {
String sql = "select * from veracodetable where output = \'" +input1 + input2+ "\'";
statement = con.createStatement();
statement.executeQuery(sql);
rs = s.getResultSet();
}
catch (Exception e) {
}
}
Something like this?
String sql = "select * from veracodetable where output = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(input1+input2);
statement.executeQuery();
rs = s.getResultSet();
Of course the PreparedStatement would have just one parameter, as you can see.

Using ResultSet to return string value from database but method skips the "Try" clause?

Why is my following code:
PrintWriter pw = response.getWriter();
pw.println(getValueOf(SQL, "lastName");
not printing anything after passing it into my method:
public static String getValueOf(String sql, String colName)
{
String result = "";
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
result = rs.getString(colName);
conn.close();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
In other words, why does it seem to be skipping the "try" clause entirely and just jumping to return the empty "" result at the end?
My SQL statment:
String SQL = "SELECT lastName FROM customers WHERE firstName=\"Bob\";";
I do have an entry for the person "Bob" (his lastname is "Mike") in my Customers table.
My Customers Table:
lastName / firstName / address / email
EDIT
It works correctly if I change the return type to "void" but I actually need a String value.
Alternate code:
public static void getValueOf(String sql, String colName, PrintWriter pw)
{
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
pw.println(rs.getString(colName)); // This does print out to the webpage as "Mike"
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Based upon your last edit, I would guess that you have more than one records.
So change your code to
if (rs.next()) {
result = rs.getString(colName);
}
And also, your code does not skip that try block

Using ResultSet to compare result within IF Statement (JAVA)

I have this piece of code where I prompt the user to enter the depID to edit a department and then through the IF statement I have done it displays either saved or department doesn't exists. Now my problem is that it's going directly to the else statement. When I used debugging I noticed that the RS (ResultSet) is only comaring the users input to the first row of the table which is AOL.
try{
String value1 = txt_depID.getText();
String value2 = txt_depName.getText();
String sql = "Update tblDepartment set depID = '"+value1+"' , depName = '"+value2+"' where depID = '"+value1+"'";
String sql1 = "Select depID, depName from tblDepartment";
Class.forName(driver);
conn = DriverManager.getConnection(url);
ps = conn.prepareStatement(sql1);
rs = ps.executeQuery();
ps = conn.prepareStatement(sql);
ps.execute();
if(rs.next()){
String depi = rs.getString("depID"); //Issue: only reading first row
if(depi.equals(value1)){
JOptionPane.showMessageDialog(null, "Entry Saved");
}
else{
JOptionPane.showMessageDialog(null, "Department doesn't exist");
}
}
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
You can do this in one cycle. You should be using executeUpdate.
String sql = "Delete from tblEmployee where staffNo=?";
String sql1 = "Select * from tblEmployee";
Class.forName(driver);
conn = DriverManager.getConnection(url);
ps = conn.prepareStatement(sql1);
int result = ps.executeUpdate();
if (result > 0) {
// success
}
Here's what executeUpdate results:
Returns: either (1) the row count for SQL Data Manipulation Language
(DML) statements or (2) 0 for SQL statements that return nothing

ResultSet not open. Operation 'moveToInsertRow' not permitted. Verify that autocommit is OFF

i'm having a trouble with this error, when i clicked the button, it'll take the values of the labels and put it in the table from database
void showAll(){
try{
rs1 = stmt.executeQuery("SELECT * FROM BORROW_RETURN");
while(rs1.next())
{
String bookpp = rs1.getString("name");
String emailse = rs1.getString("email");
String booktee = rs1.getString("book_title");
String ser_no = rs1.getString("serial_no");
String borr = rs1.getString("borrowed");
String ret = rs1.getString("return");
loginModel3.addRow(new Object[]{bookpp, emailse, booktee, ser_no, borr, ret});
}}catch(SQLException err){
System.out.print(err);
}
}
and this is the connection to the connection to the database
void DoConnect1( ) {
try{
String host = "jdbc:derby://localhost:1527/Dafuq7";
String uName ="Dafuq7";
String uPass ="Dafuq7";
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM borrow_return";
rs1 = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
}
and upon clicking the button the said error occurs,
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String ema = jLabel20.getText();
String enm = jLabel21.getText();
String booknm = bttl.getText();
String snnnn = sernum.getText();
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dates = dateFormat.format(date_borr.getDate());
try {
rs1.moveToInsertRow();
rs1.updateString( "book_title", booknm );
rs1.updateString( "serial_no", snnnn );
rs1.updateString( "name", enm );
rs1.updateString( "email", ema );
rs1.updateString( "borrowed", dates );
JOptionPane.showMessageDialog(null, "HAHA");
loginModel3.addRow(new Object[]{names, booknm, snnnn, enm, ema, dates});
con.setAutoCommit(false);
System.out.println(con.getAutoCommit());
rs1.insertRow( );
stmt.close();
rs1.close();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM accounts";
rs1 = stmt.executeQuery(sql);
}
catch (SQLException err) {
System.out.println(err.getMessage() );
}
}
You are setting autoCommit to false after your queries are really committed. You need to set it false once after you open connection or before start executing your queries.
con = DriverManager.getConnection(host, uName, uPass);
//EXECUTE SOME SQL AND LOAD THE RECORDS INTO THE RESULTSET
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM borrow_return";
con.setAutoCommit(false);
rs1 = stmt.executeQuery(sql);
https://codedump.io/share/WK0Jtw7GEH3h/1/why-do-i-get-javasqlsqlexception-resultset-not-open-operation-39next39-not-permitted-java-derby-database
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

Categories

Resources