JDBC Delete All Rows In Table Example


 

JDBC Delete All Rows In Table Example

In this tutorial provide the example of how to delete all records from table using mysql JDBC driver.

In this tutorial provide the example of how to delete all records from table using mysql JDBC driver.

JDBC Delete All Rows In Table Example:

 In this tutorial provide the example of  how to delete  all records from table using mysql  JDBC driver. This tutorial  use the "com.mysql.jdbc.Driver"  driver and java class "DeleteAllRows" that import all related class and also defined all related variable .

          This tutorial first  import all related classes, register the JDBC driver, open the connection from database server, again create query and   execute. There use mysql query "DELETE FROM user"  that execute and delete all records from table and display output "Deleted All Rows In The Table Successfully...". If  database or table not exist give run time exception. If table already empty then count  deleted rows o and display output "Table already empty.". The "DeleteAllRows.java" code given below as:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
  
public class DeleteAllRows{
	// 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";
				int deletedRows=stmt.executeUpdate(query);
				if(deletedRows>0){
				     System.out.println("Deleted All Rows In The Table Successfully...");
				   }else{
                                System.out.println("Table already empty."); 
				  }
								
			   } catch(SQLException s){
					System.out.println("Deleted All Rows In  Table Error. ");		
					s.printStackTrace();
				 }
			// close Connection
			con.close();
			}catch (Exception e){
				e.printStackTrace();
			 }
	}
}


<

Program Output :

F:\jdbc>javac DeleteAllRows.java

F:\jdbc>java DeleteAllRows
Deleted All Rows In The Table Successfully...

F:\jdbc>java DeleteAllRows
Table already empty.

F:\jdbc>

Download Code

Ads