Minggu, 01 November 2015

JAVA And MySQL - How To Search Data In MySQL Database And Display It In JTable Using Java

JAVA Code - How To Filter Data From MySQL Database And Show It In JTable Using Java NetBeans

__________________________________________________________________________

In this java Tutorial we will learn How To Find Data In MySQL Database With A Specific 
Value From JTextField And Display The Result In JTable In Java NetBeans .


*Java Courses Java Complete Course

                            Java Swing Course

java jtable mysql find


                                                                  Part 1



Part 2


Project Source Code:

// Create Class User


package JAVA_VIDEOS_TUTORIALS;

public class User {

private int id;
private String fname;
private String lname;
private int age;


public User(int Id,String Fname,String Lname,int Age)
{
this.id = Id;
this.fname = Fname;
this.lname = Lname;
this.age = Age;
}

public int getId()
{
return id;
}

public String getFname()
{
return fname;
}

public String getLname()
{
return lname;
}

public int getAge()
{
return age;
}
}

      
// Creates new form JTable_Search
package JAVA_VIDEOS_TUTORIALS;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;

/**
*
* @author 1BestCsharp
*/
public class JTable_Search extends javax.swing.JFrame {

/**
* Creates new form JTable_Search
*/
public JTable_Search() {
initComponents();


// call findUsers function
findUsers();


}


// function to connect to mysql database
public Connection getConnection()
{
Connection con = null;

try{
con = DriverManager.getConnection("jdbc:mysql://localhost/test_db","root","");
}catch(Exception ex){
System.out.println(ex.getMessage());
}

return con;
}


// function to return users arraylist with particular data
public ArrayList<User> ListUsers(String ValToSearch)
{
ArrayList<User> usersList = new ArrayList<User>();

Statement st;
ResultSet rs;

try{
Connection con = getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery(searchQuery);

User user;

while(rs.next())
{
user = new User(
rs.getInt("id"),
rs.getString("fname"),
rs.getString("lname"),
rs.getInt("age")
);
usersList.add(user);
}

}catch(Exception ex){
System.out.println(ex.getMessage());
}

return usersList;
}


// function to display data in jtable
public void findUsers()
{
ArrayList<User> users = ListUsers(jText_Search.getText());
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[]{"ID","Fname","Lname","Age"});
Object[] row = new Object[4];

for(int i = 0; i < users.size(); i++)
{
row[0] = users.get(i).getId();
row[1] = users.get(i).getFname();
row[2] = users.get(i).getLname();
row[3] = users.get(i).getAge();
model.addRow(row);
}
jTable_Users.setModel(model);

}



@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel2 = new javax.swing.JPanel();
jButton_Search = new javax.swing.JButton();
jText_Search = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable_Users = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jButton_Search.setText("Search");
jButton_Search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_SearchActionPerformed(evt);
}
});

jText_Search.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N

jTable_Users.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jTable_Users.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable_Users);

javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap(22, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jText_Search, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton_Search)
.addGap(136, 136, 136))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 500, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29))))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton_Search)
.addComponent(jText_Search, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(41, Short.MAX_VALUE))
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

pack();
}// </editor-fold>
 
                        
    // Button Filter/search 

private void jButton_SearchActionPerformed(java.awt.event.ActionEvent evt) {

findUsers();

}


/**
* @param args the command line arguments
*/
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JTable_Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JTable_Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JTable_Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JTable_Search.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JTable_Search().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton_Search;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable_Users;
private javax.swing.JTextField jText_Search;
// End of variables declaration
}


// OUTPUT:
java jtable filter
Java JTable Data From Mysql Search

Bagikan

Jangan lewatkan

JAVA And MySQL - How To Search Data In MySQL Database And Display It In JTable Using Java
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.