How to Select Records
Selecting records in a database means retrieving data (rows) from a table using the SQL SELECT statement.
Example: Selecting Records in Java
Source Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.swing.JOptionPane;
public class Insertstudent extends javax.swing.JFrame{
Connection conn;
PreparedStatement pst;
ResultSet rs;
public Insertstudents() {
initComponents();
connect();
}
public void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost/studentdb?useSSL=false&serverTimezone=Asia/Phnom_Penh";
String user = "root";
String pass = "root";
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
}
private void btnSelectActionPerformed(java.awt.event.ActionEvent evt) {
String id = txtID.getText().trim();
if (id.isEmpty()) {
JOptionPane.showMessageDialog(this, "Please enter an ID");
return;
}
try {
pst = conn.prepareStatement("SELECT * FROM students WHERE id = ?");
pst.setInt(1, Integer.parseInt(id));
rs = pst.executeQuery();
if (rs.next()) {
// Fill text fields with database values
txtName.setText(rs.getString("name"));
txtGender.setText(rs.getString("gender"));
txtAddress.setText(rs.getString("address"));
txtPhone.setText(rs.getString("phone"));
} else {
JOptionPane.showMessageDialog(this, "No Record Found!");
// clear fields if not found
txtName.setText("");
txtGender.setText("");
txtAddress.setText("");
txtPhone.setText("");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Result:
Watch the video:
Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html
.png)
