CodesJava

Easy learning with example program codes

Delete record using PreparedStatement JDBC

The JDBC PreparedStatement is used to execute parameterized queries against the database. Let us study JDBC PreparedStatement by deletes a record example.

Example:

JDBCTest.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import com.codesjava.util.JDBCUtil;
 
/**
 * This class is used to delete a record from DB table
 * using PreparedStatement.
 * @author codesjava
 */
public class JDBCTest {
	public static void main(String args[]){
		Connection conn = null;
		PreparedStatement preparedStatement = null;
 
		String query = "delete EMPLOYEE " + 
		"where EMPLOYEE_ID = 1 ";
 
		try{
			//get connection
			conn = JDBCUtil.getConnection();
 
			//create preparedStatement
			preparedStatement = conn.prepareStatement(query);
 
			//execute query
			preparedStatement.executeUpdate();
 
			//close connection
			preparedStatement.close();
			conn.close();
 
		     System.out.println("Record deleted successfully.");
		}catch(Exception e){
			e.printStackTrace();
		}
	}	
}

JDBCUtil.java

import java.sql.Connection;
import java.sql.DriverManager;
 
/**
 * This is a utility class for JDBC connection.
 * @author codesjava
 */
public class JDBCUtil {
	//JDBC and database properties.
	private static final String DB_DRIVER = 
		           "oracle.jdbc.driver.OracleDriver";
	private static final String DB_URL = 
		        "jdbc:oracle:thin:@localhost:1521:XE";
	private static final String DB_USERNAME = "system";
	private static final String DB_PASSWORD = "oracle";
 
	public static Connection getConnection(){
		Connection conn = null;
		try{
			//Register the JDBC driver
			Class.forName(DB_DRIVER);
 
			//Open the connection
			conn = DriverManager.
			getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
 
			if(conn != null){
			   System.out.println("Successfully connected.");
			}else{
			   System.out.println("Failed to connect.");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return conn;
	}	
}

Output:

Successfully connected.
Record deleted successfully.

Download this example.
 
Next Topic: JDBC PreparedStatement batch update example.
Previous Topic: JDBC PreparedStatement select records example.

 

Please follow and like us:
error
Posted in JDBC   








Copyright © 2019 CodesJava DMCA.com Protection Status