Home Tutorial Java Swing Show multiple identical rows into JTable from database

 
 

Share on Google+Share on Google+
Show multiple identical rows into JTable from database
Posted on: December 21, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to display the multiple rows from database to JTable.

Show multiple identical rows into JTable from database

In this tutorial, you will learn how to display the multiple rows from database to JTable. Here is an example that search the data from the database and show multiple identical rows from database on clicking search button to jtable. The given code accepts the name from the user and search the same name into database. If it founds, then all the data associated with that name will get displayed into JTable rows.

Example:

import java.awt.*;
import java.sql.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;

class Search{
public static void main(String[] args) {
final Vector columnNames = new Vector();
final Vector data = new Vector();

JLabel lab=new JLabel("Enter Name:");
final JTextField t=new JTextField(20);
JButton b = new JButton("Search");
JPanel p = new JPanel(new GridLayout(2,2));
p.add(lab);
p.add(t);
p.add(b);
JFrame f = new JFrame();
f.getContentPane().add(p);
f.pack();
f.setVisible(true);

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String name=t.getText();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from data where name='"+name+"'");
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++){
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
JFrame frame=new JFrame();
JTable table = new JTable(data, columnNames);

JScrollPane pane=new JScrollPane(table);

frame.add(pane);
frame.setVisible(true);
frame.pack();
}
catch(Exception ex){
System.out.println(e);
}
}
});
}
}
Advertisement

Related Tags for Show multiple identical rows into JTable from database:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 21, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com