JDBC Delete Row In Table Example


 

JDBC Delete Row In Table Example

In this tutorial we will learn how delete specific row from the table use mysql JDBC driver.

In this tutorial we will learn how delete specific row from the table use mysql JDBC driver.

JDBC Delete Row In Table Example :

In this tutorial we will learn how delete specific row from the table use mysql JDBC driver.This tutorial defined how one or more specific  row delete from table that follow any given condition. If any datrabase or table not exist first create and enter record to the table.

         We  follow the steps in "DeleteRow.java" class that given step by step as:
1.Import the packages
2.Register the JDBC driver
3.Open a connection
4.Execute a query

 Mysql query  "DELETE FROM user where user_id=1 "   that  delete the user's row  which "user_id=1".If  delete row then count deleted row and display output "Deleted specific row in the  table successfully..."  another display error message "Not exist specific row that you select for delete". The code of "DeleteRow.java" class is:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
  
public class DeleteRow{
// JDBC driver name and database URL
static String driverName = "com.mysql.jdbc.Driver";
static String url = "jdbc:mysql://localhost:3306/";

// defined and set value in  dbName, userName and password variables
static String dbName = "testjdbc";
static String userName = "root";
static String password = "";

public static void main(String[] args){
// create Connection con, and Statement stmt 
Connection con;
Statement stmt;
try{
	Class.forName(driverName).newInstance();
	con = DriverManager.getConnection(url+dbName, userName, password);
	try{
		stmt = con.createStatement();
		String query = "DELETE FROM user where user_id=1 ";
		int count=stmt.executeUpdate(query);
		if(count>0){
			  System.out.println("Deleted Specific Row in the  table successfully...");
		   }else{
			 System.out.println("Not exist specific row that you select for delete");
		  }			
	   } catch(SQLException s){						
			s.printStackTrace();
		 }
	// close Connection
	con.close();
	}catch (Exception e){
		e.printStackTrace();
	 }
}
}

Program Output :

F:\jdbc>javac DeleteRow.java

F:\jdbc>java DeleteRow
Deleted specific row in the table successfully...

F:\jdbc>java DeleteRow
Not exist specific row that you select for delete

F:\jdbc>

Download Code

Ads