9:10 am - Thursday February 22, 2018

Statement DELETE Example program in java Jdbc mysql database

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

Delete statement:

This tutorial explains how to delete a single row from a table in mysql using java statement example, Load the mysql driver using Class.forName method and create a connection to communicate with mysql database and then create a statement object to send and receive from java code and use executeUpdate to execute the query. If user wants to delete a one or more rows from a table delete query will helps us to do it. Suppose if we want to delete the details of ravi from student table we can use this sample code to delete it.

create table:


 create table student(Roll_No int(5),Name varchar(25),

Department varchar(7),Address varchar(30));

Query OK, 0 rows affected (0.06 sec)

Input:

Java code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Delete {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String Driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost/test";
		String uName ="root";
		String pwd = "root";
		Connection conn=null;

		try {
			Class.forName(Driver).newInstance();
			conn = DriverManager.getConnection(url, uName, pwd);
			Statement stmt = conn.createStatement();
			String sql = "delete from student where name='ravi'";
			stmt.executeUpdate(sql);
			System.out.println("Data deleted sucessfully");

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

OUTPUT:

 

Data deleted successfully

Filed in: Z-A All Java Codes

Comments are closed.