How to fetch data in JTable
843859Sep 21 2006 — edited Oct 10 2006I wanna know how to display the data returned from the database in a Table. I am providing the code in which i am unable to display the data in a Table.
/*
<HTML>
<Applet Code="SQLWithTable.class" width=600 height=600>
</Applet>
</HTML>
*/
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class SQLWithTable extends JApplet implements ActionListener
{
Container c;
String[] colHead=null;
Object[][] data=null;
Connection con;
ResultSet result;
JLabel lquery;
JTextField tquery;
JButton bsubmit;
JButton clear;
String query;
public void init()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection"jdbc:odbc:MyDataSource","sa","");
System.out.println("Connected To DataBase Server");
}
catch(Exception e)
{
System.out.println("Error Loading Driver");
}
c=getContentPane();
c.setLayout(new FlowLayout());
lquery=new JLabel("Enter Query");
tquery=new JTextField(20);
bsubmit=new JButton("Execute");
c.add(lquery);
c.add(tquery);
c.add(bsubmit);
bsubmit.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
query=tquery.getText(); //get query from user
Object obj=(JButton)evt.getSource();
if(obj==bsubmit)
{
try
{
Statement stat=con.createStatement();
ResultSet result=stat.executeQuery(query);
ResultSetMetaData rsmd=result.getMetaData();
int colCount=rsmd.getColumnCount();
for(int i=1; i<=colCount; i++)
{
//How to display the columnHeadings in Table
}
while(result.next())
{
for(int i=1; i<=colCount; i++)
{
//How to insert data in Table
}
}
JTable table=new JTable(data,colHead);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(table,v,h);
c.add(jsp);
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}