PR 18
PR 18
Code :
import l2 = new Label("Enter
java.sql.Connection; Name:");
import l2.setBounds(20, 100,
java.sql.DriverManager; 100, 30);
import l2.setFont(new
java.sql.PreparedStatemen Font("Arial", Font.BOLD,
t; 15));
import java.sql.ResultSet; t1 = new TextField();
import t1.setBounds(150, 50,
java.sql.SQLException; 200, 30);
import java.awt.*; t2 = new TextField();
import java.awt.event.*; t2.setBounds(150,
import javax.swing.*; 100, 200, 30);
public class Dbconnection submitBtn = new
extends JFrame Button("Submit");
implements ActionListener
{ submitBtn.setBounds(50,
TextField t1, t2; 160, 100, 30);
Label l1, l2;
Button submitBtn, submitBtn.addActionListen
clearBtn; er(this);
Connection con; clearBtn = new
Dbconnection() { Button("Clear");
l1 = new Label("Enter
Roll no:"); clearBtn.setBounds(180,
l1.setBounds(20, 50, 160, 100, 30);
100, 30);
clearBtn.addActionListener
l1.setFont(new
(this);
Font("Arial", Font.BOLD,
add(l1);
15));
add(t1);
add(l2);
add(t2); String marks =
add(submitBtn); t1.getText();
add(clearBtn); String name =
setTitle("Database t2.getText();
Connection Form"); if (!marks.equals("") && !
setSize(400, 300); name.equals("")) { //
setLayout(null); Use .equals("") for string
setVisible(true); comparison
try {
setDefaultCloseOperation(J
Frame.EXIT_ON_CLOSE); PreparedStatement pstmt
try { =
con.prepareStatement("IN
Class.forName("com.mysql SERT INTO stud VALUES (?,
.jdbc.Driver");con = ?)");
DriverManager.getConnect
ion("jdbc:mysql://localhost pstmt.setString(1, marks);
:3306/student", "root", "");
pstmt.setString(2, name);
System.out.println("Conne int i =
ction Established pstmt.executeUpdate();
Successfully!!!"); if (i > 0) {
} catch
(ClassNotFoundException | System.out.println("Data
SQLException e) { Inserted Successfully");
}
e.printStackTrace();
} PreparedStatement
} pstmt1 =
public static void con.prepareStatement("SE
main(String[] args) { LECT * FROM stud WHERE
new Dbconnection(); s_name=?");
}
@Override pstmt1.setString(1,
public void name);
actionPerformed(ActionEv ResultSet rs =
ent e) { pstmt1.executeQuery();
if (e.getSource() == while
submitBtn) { (rs.next()) {
} catch
JOptionPane.showMessage (SQLException ex) {
Dialog(this,
"Data ex.printStackTrace();
Inserted Successfully \ }
nInserted Data: " + } else {
rs.getString(1) + " " +
rs.getString(2), JOptionPane.showMessage
Dialog(this, "Please fill in
"SuccessFully", all fields", "Error",
JOptionPane.INFORMATION
_MESSAGE);
}
System.out.print("Name of
student who have greater
than 75 marks: \n");
PreparedStatement
pstmt2=con.prepareState
ment("select * from stud
where marks >=75");
ResultSet
rs1=pstmt2.executeQuery(
);
while(rs1.next())
{
System.out.print("Name Of
Student:"+rs1.getString(2)
); JOptionPane.ERROR_MESS
AGE);
System.out.print("\
}
n");
}
}
if
t1.setText("");
t2.setText("");
(e.getSource() ==
clearBtn) {
t1.setText("");
t2.setText("");
}
}
}