Write a Java program to accept details of Doctor(dno, dname, salary) from the user and insert it into the database(Use PreparedStatement class and AWT).

Write a Java program to accept details of Doctor(dno, dname, salary) from the user and insert it into the database(Use PreparedStatement class and AWT).



Program:
import java.io.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;

public class Doctor extends Frame implements ActionListener {
    Label labelDNo, labelDName, labelSalary;
    TextField textDNo, textDName, textSalary;
    Button btnAdd; btnExit;

    public Doctor() {
        labelDNo = new Label("Doctor No:");
        labelDName = new Label("Doctor Name:");
        labelSalary = new Label("Doctor Salary:");

        textDNo = new TextField(20);
        textDName = new TextField(20);
        textSalary = new TextField(20);

        btnAdd = new Button("Add");
        btnExit = new Button("Exit");

        setLayout(new GridLayout(4,2));
        add(labelDNo);
        add(textDNo);
        add(labelDName);
        add(textDName);
        add(labelSalary);
        add(textSalary);
        add(btnAdd);
        add(btnExit);

        btnAdd.addActionListener(this);
        btnExit.addActionListener(this);

        setVisible(true);
        setSize(500,500);
    }

    public static void main(String args[]) {
        new Doctor();
    }

    public void actionPerformed(ActionEvent ae){
        if(ae.getSource() == btnExit){
            System.exit(0);
        }

        if(ae.getSource == btnAdd) {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                COnnection con = DriverManager.getConnection("jdbc:odbc:doctorDSN");
                PreparedStatement ps = con.prepareStatement("insert into doctor values(?,?,?)");
                ps.setInt(1, Integer.parseInt(textDNo.getText()));
                ps.setString(2, textDName.getText());
                ps.setInt(3, Integer.parseInt(textSalary.getText()));
                ps.execute();
                JOptionPane.showMessageDialog(null, "Values inserted.");
                con.close();
            } catch(Exception e) {
                System.out.println(e);
            }
        }
    }
}

Post a Comment

Previous Post Next Post