Post Views: 2
Write a Java program to display first record from student table (rno, sname, per) onto the TextFields by clicking on button. (Assume Student table is already created).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class StudentRecordDisplay extends JFrame implements ActionListener {
// Labels
JLabel lRno, lName, lPer;
// TextFields
JTextField tRno, tName, tPer;
// Button
JButton btnFirst;
// JDBC
Connection con;
Statement stmt;
ResultSet rs;
public StudentRecordDisplay() {
// Frame setup
setTitle("Student Record Display");
setSize(400, 250);
setLayout(new GridLayout(4, 2, 10, 10));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Initialize Labels
lRno = new JLabel("Roll No:");
lName = new JLabel("Name:");
lPer = new JLabel("Percentage:");
// Initialize TextFields
tRno = new JTextField();
tName = new JTextField();
tPer = new JTextField();
// Make textfields non-editable
tRno.setEditable(false);
tName.setEditable(false);
tPer.setEditable(false);
// Initialize Button
btnFirst = new JButton("Show First Record");
btnFirst.addActionListener(this);
// Add components to frame
add(lRno); add(tRno);
add(lName); add(tName);
add(lPer); add(tPer);
add(new JLabel()); add(btnFirst); // Empty label for spacing
// Make frame visible
setVisible(true);
// Setup JDBC
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "root", "root");
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT * FROM Student");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Database Error: " + e);
}
}
@Override
public void actionPerformed(ActionEvent ae) {
try {
if(rs != null && rs.first()) { // Move cursor to first record
tRno.setText(String.valueOf(rs.getInt("rno")));
tName.setText(rs.getString("sname"));
tPer.setText(String.valueOf(rs.getDouble("per")));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error: " + e);
}
}
public static void main(String[] args) {
new StudentRecordDisplay();
}
}