JDBC ResultSet Delete Row Example


 

JDBC ResultSet Delete Row Example

Learn how to delete row using ResultSet. We are also used ResultSet object with update capability for delete rows from database tables.

Learn how to delete row using ResultSet. We are also used ResultSet object with update capability for delete rows from database tables.

JDBC ResultSet Delete Row Example:

Learn how to delete row using ResultSet. We are also used ResultSet object with update capability for delete rows from database tables. The following step are use:

1. Create a database connection object.

2. Create a statement object with ResultSet.CONCUR_UPDATABLE concurrency type.

3. Create a SQL select query.

4. Execute query using executeQuery() method on the created statement object to return ResultSet object on the table.

5. Call ResultSet methods like next(), absolute(), last() etc for cursor move.

6. Finally call deleteRow() ResultSet method for delete the current row form the table of the ResultSet object.

Example:

package ResultSet;
import java.sql.*;

public class ResultSetDeleteRow {

  public static void main(String[] args) {
    
        Connection connection = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "roseindia_jdbc_tutorials";
        String driverName = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "root";

        try {
          Class.forName(driverName).newInstance();
          connection = DriverManager.getConnection(url+dbName, userName, password);
         
          Statement stmt = connection.createStatement(
              ResultSet.TYPE_SCROLL_SENSITIVE,
              ResultSet.CONCUR_UPDATABLE);
          
            ResultSet rs = stmt.executeQuery("SELECT * from user");
            while(rs.next()){
              if(rs.getInt(1)==1){
                rs.deleteRow();
                System.out.println("Deleted user_id :" + rs.getInt(1));
              }
              else{
                System.out.println("user_id :" + rs.getInt(1));
              }
            }                  
            rs.close();
            stmt.close();
            connection.close();
        catch (Exception e) {
          System.err.println(e);
        }  
   }
}
 

In this example we are deleting row that have user_id == 1.

Now we will run this example with the help of eclipse IDE and see the output.

Program output:

The database table output before run the example is:

The eclipse console output is:

The database table output after run example is:

Download source code

Ads