A) Java Program to Demonstrate JDBC with DML Statements Using Prepared Statements and Callable Statements
Fri Nov 01 2024 14:11:34 GMT+0000 (Coordinated Universal Time)
Saved by @abhigna
import java.sql.*;
public class JdbcDmlExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace with your database name
String user = "your_username"; // Replace with your database username
String password = "your_password"; // Replace with your database password
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// Prepared Statement for Insert
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(insertSQL)) {
pstmt.setString(1, "John Doe");
pstmt.setString(2, "john@example.com");
pstmt.executeUpdate();
System.out.println("User inserted successfully.");
}
// Prepared Statement for Update
String updateSQL = "UPDATE users SET email = ? WHERE name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(updateSQL)) {
pstmt.setString(1, "john.doe@example.com");
pstmt.setString(2, "John Doe");
pstmt.executeUpdate();
System.out.println("User updated successfully.");
}
// Prepared Statement for Delete
String deleteSQL = "DELETE FROM users WHERE name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(deleteSQL)) {
pstmt.setString(1, "John Doe");
pstmt.executeUpdate();
System.out.println("User deleted successfully.");
}
// Callable Statement for retrieving users
String callableSQL = "{CALL getAllUsers()}"; // Assume this stored procedure exists
try (CallableStatement cstmt = conn.prepareCall(callableSQL)) {
ResultSet rs = cstmt.executeQuery();
System.out.println("Users in the database:");
while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
How to Run the Java Program
Setup JDBC: Ensure you have the MySQL JDBC Driver in your classpath.
Create a Java File: Save the code above in a file named JdbcDmlExample.java.
Create the Database and Table: Ensure you have a database with a users table that has at least id, name, and email columns. Also, create a stored procedure getAllUsers to fetch users.
Compile and Run: Compile and run the Java program. Update the placeholders with your actual database connection details.



Comments