Sunday, 13 September 2015

How To Load DataBase Data In Jtable

When dealing with database programs we often need to load or connect our database data in jtable in these tutorial we showed how to load whole database data in jtable.In  the following program we have used following methods:

RELATED TUTORIALS:

ResultSet ExecuteQuery:

As you can see its return type is resultset so it returns resultset it has been used with select statement.

GetString:

This method is used to get string from specified column.

CODING:

import javax.swing.*; 
import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.table.DefaultTableModel;

class myjframe1 extends JFrame
{
DefaultTableModel model;
String rowData[][];
JTable table;
String s,s1,s2;
public myjframe1()
{

setTitle("Loading DataBase Data");
setSize(300, 200);

setDefaultCloseOperation(EXIT_ON_CLOSE);      

String columnNames[] = { "NAME", "EMAIL", "PHONE NUMBER" };


model = new DefaultTableModel(rowData, columnNames);
JTable table = new JTable(model);
setLayout(new FlowLayout(FlowLayout.CENTER));
JScrollPane js = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(js);
create();
setVisible(true);

}
private  void  create()
{

try{
Statement st;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:login");
st=cn.createStatement();
ResultSet data;


data=st.executeQuery("select * from load");
while(data.next())
{
s = data.getString(1);
s1 = data.getString(2);
s2 = data.getInt(3);
model.addRow(new String[]{s,s1,s2});
}
st.close();
cn.close();
data.close();

}
catch(ClassNotFoundException e)
{
System.out.print(e);

} catch (SQLException e) {
System.out.print(e);
}

}

}

class pra
{
public static void main(String args[])
{
myjframe1 x= new myjframe1();
}
}

OUTPUT:


No comments:

Post a Comment