How to search for data on a database through Java GUI. We will be using a list to search for data in a table according to its primary key and showing its details on the text-fields.
![]() |
JDBC |
import java.sql.*;
try {
Class.forName(“com.mysql.jdbc.Driver”);
Connection con= (Connection) DriverManager.getConnection(“jdbc:mysql://localhost:3306/database1“,”root”,””);
Statement stmt=con.createStatement();
String num = (String) jList1.getSelectedValue();
String sql1 = “Select * from library where no = ‘” + (num) + “‘”;
ResultSet rs = stmt.executeQuery(sql1);
while (rs.next())
{
String no = rs.getString(“NO”);
String title= rs.getString(“TITLE”);
String auth= rs.getString(“AUTHOR”);
jTextField1.setText(“”+no);
jTextField2.setText(“”+title);
jTextField3.setText(“”+auth);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
7 Change the codes in blue according to your database. Finally, run the file(Shift +F6)
![]() |
|
Run View |
Add some labels and uncheck the editable property of text-fields to make the design look better.
After searching the data, you can allow users to update or delete rows.
// watch a video tutorial for java database connectivity on the videos page