Wednesday, 12 December 2012

java swing program to retrive data from database and display using JTABLE



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

class ShowFrame extends JFrame
{
ShowFrame()
{ try
{



JTable tab = new JTable();
  JScrollPane sc=new JScrollPane(tab);
DefaultTableModel df=new DefaultTableModel();
add(sc);

Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost/nirav","root","root");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery("select * from t1 ");


ResultSetMetaData meta= rs.getMetaData();
int count=meta.getColumnCount();
String c[]=new String[count];
for(int i=0;i<count;i++)
{
c[i]=meta.getColumnName(i+1);
df.addColumn(c[i]);
}


Object row[]=new Object[count];
while(rs.next())
{
for(int i=0;i<count;i++)
{
row[i]=rs.getString(i+1);
}
df.addRow(row);
}

tab.setModel(df);
//add(pan);
rs.close();
  cn.close();
}
catch(Exception e)
{
}
}

             }


class MainRetrive
{
public static void main(String str[])
{
ShowFrame sf=new ShowFrame();
//sf.setSize(200,200);
sf.setBounds(200,200,400,300);
sf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sf.setVisible(true);

}

}