Slip No 9 Q A

Write a Java Program to create a Emp (ENo, EName, Sal) table and insert record into it. (Use PreparedStatement Interface)

import java.sql.*;

public class EmpPreparedStatement {

    public static void main(String[] args) {

        // Database details
        String url = "jdbc:mysql://localhost:3306/testdb";
        String user = "root";
        String password = "root";

        try {
            // Load MySQL JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish Connection
            Connection con = DriverManager.getConnection(url, user, password);
            System.out.println("Connection Established");

            // Create Emp Table
            String createTable = "CREATE TABLE IF NOT EXISTS Emp ("
                    + "ENo INT PRIMARY KEY, "
                    + "EName VARCHAR(50), "
                    + "Sal DOUBLE)";

            Statement stmt = con.createStatement();
            stmt.executeUpdate(createTable);
            System.out.println("Emp Table Created");

            // Insert Record using PreparedStatement
            String insertQuery = "INSERT INTO Emp VALUES (?, ?, ?)";
            PreparedStatement ps = con.prepareStatement(insertQuery);

            ps.setInt(1, 101);
            ps.setString(2, "Amit");
            ps.setDouble(3, 35000.50);

            ps.executeUpdate();
            System.out.println("Record Inserted Successfully");

            // Close connection
            ps.close();
            stmt.close();
            con.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top