Share on Google+Share on Google+

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.

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 "" 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;
			con = DriverManager.getConnection(url+dbName, userName, password);
				stmt = con.createStatement();
				String query = "DELETE FROM user";
				int deletedRows=stmt.executeUpdate(query);
				     System.out.println("Deleted All Rows In The Table Successfully...");
                                System.out.println("Table already empty."); 
			   } catch(SQLException s){
					System.out.println("Deleted All Rows In  Table Error. ");		
			// close Connection
			}catch (Exception e){


Program Output :


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

F:\jdbc>java DeleteAllRows
Table already empty.


Download Code



Posted on: October 15, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null