Prepared Statement JDBC

PHOTO EMBED

Sun Nov 03 2024 16:03:11 GMT+0000 (Coordinated Universal Time)

Saved by @signup_returns #html

//Prepared Statement

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

public class StatementDemo {
    public static void main(String[] args) {
        String DB_URL = "jdbc:oracle:thin:@//localhost:1521/XE";
        String user = "system";
        String pass = "1234";

        try (Connection conn = DriverManager.getConnection(DB_URL, user, pass)) {
            String insertQuery = "INSERT INTO employee(name, salary) VALUES (?, ?)";
            try (PreparedStatement pstmt = conn.prepareStatement(insertQuery)) {
                pstmt.setString(1, "Jack");
                pstmt.setDouble(2, 300000);
                pstmt.executeUpdate();
                System.out.println("Sucessfully Inserted a record");
            }

            String getQuery = "SELECT * FROM employee WHERE salary > ?";
            try (PreparedStatement pstmt = conn.prepareStatement(getQuery)) {
                pstmt.setDouble(1, 350000);
                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                    String str = rs.getString("name");
                    double sal = rs.getDouble("salary");

                    System.out.println("Employee Name: " + str + ", Salary is: " + sal);

                }
            }

        } catch (SQLException se) {
            System.out.println("An error occured");
            se.printStackTrace();
        }
    }
}
content_copyCOPY