JDBC: Delete Record using Prepared Statement


 

JDBC: Delete Record using Prepared Statement

In this section, we will discuss how to delete row of a table using Prepared Statements.

In this section, we will discuss how to delete row of a table using Prepared Statements.

JDBC: Delete Record using Prepared Statement

In this section, we will discuss how to delete row of a table using Prepared Statements.

Delete Record   : Prepared statement is good to use where you need to execute same SQL statement many times for different values. It is precompiled SQL Statements which are stored in a PreparedStatement object. Now you can use this object to execute this statement many times. It is the best way to reduce execution time and improve performance. So if you want to delete many rows, you can use Prepared statement.
You can delete any specific record under some condition using WHERE Clause. So you can delete one row or multiple row of table as specified condition.

executeUpdate(String sql): This method executes SQL statements(insert, update or delete)in PreparedStatement object, which takes the SQL query of string type and returns int.

Example : In this example, we are deleting record of student whose roll_no is 3  using prepared statement.

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

class PreparedStatementDelete {
	public static void main(String[] args) {
		System.out.println("Delete Record using PreparedStatement...");
		Connection con = null;
		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "students";
		String driverName = "com.mysql.jdbc.Driver";
		String userName = "root";
		String password = "root";
		PreparedStatement st = null;
		try {
			Class.forName(driverName);
			con = DriverManager.getConnection(url + dbName, userName, password);
			try {

				// Delete record
				String sql = "DELETE FROM student WHERE roll_no=?";
				st = con.prepareStatement(sql);
				st.setInt(1,5);
				st.executeUpdate();
				System.out.println("Row deleted successfully");

			} catch (SQLException s) {
				System.out.println(s);
			}
			con.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output :

Delete Record using PreparedStatement...
Row deleted successfully

Ads