jdbc prepared( update-insert-select) statement

PHOTO EMBED

Fri Nov 15 2024 12:27:51 GMT+0000 (Coordinated Universal Time)

Saved by @wtlab

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

public class DatabaseOperations {
    public static void main(String[] args) throws ClassNotFoundException {
        String jdbcUrl = "jdbc:oracle:thin:@//localhost:1521/XE";
        String user = "system";
        String password = "hari123";
        
        try {
            // Load Oracle JDBC Driver
            Class.forName("oracle.jdbc.driver.OracleDriver");

            // Establish connection
            Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
            System.out.println("Connection established successfully");

            // 1. Insert Operation with PreparedStatement
            String insertSQL = "INSERT INTO Users (username, password, email) VALUES (?, ?, ?)";
            PreparedStatement insertStatement = connection.prepareStatement(insertSQL);
            insertStatement.setString(1, "hari");
            insertStatement.setString(2, "secure@123");
            insertStatement.setString(3, "john@example.com");
            int insertResult = insertStatement.executeUpdate();
            System.out.println(insertResult + " row(s) inserted.");
            insertStatement.close();

            // 2. Select Operation with PreparedStatement
            String selectSQL = "SELECT * FROM Users";
            PreparedStatement selectStatement = connection.prepareStatement(selectSQL);
            ResultSet rs = selectStatement.executeQuery();
            while (rs.next()) {
                System.out.println("Username: " + rs.getString("username") +
                                   ", Password: " + rs.getString("password") +
                                   ", Email: " + rs.getString("email"));
            }
            selectStatement.close();

            // 3. Update Operation with PreparedStatement
            String updateSQL = "UPDATE Users SET email = ? WHERE username = ?";
            PreparedStatement updateStatement = connection.prepareStatement(updateSQL);
            updateStatement.setString(1, "john_new@example.com");
            updateStatement.setString(2, "john_doe");
            int updateResult = updateStatement.executeUpdate();
            System.out.println(updateResult + " row(s) updated.");
            updateStatement.close();

            // Close the connection
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
content_copyCOPY