I am new to Java language.. I want to display records from Mysql database into JTable.. But i'm getting only one row.. I've no idea where i'm going wrong. Any help would higly be appreciated.
My code is:
package test;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.sql.*;
import net.proteanit.sql.DbUtils;
class Test {
JFrame frame;
Container pane;
JTable table;
Connection con;
Statement sth;
ResultSet rs;
public void connect () {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/SMS", "root", "phplover");
} catch (Exception e) {
System.out.println("Conection failed. " + e);
}
}
public void initGUI () {
frame = new JFrame();
frame.setVisible(true);
frame.setBounds(100, 100, 500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane = frame.getContentPane();
}
public void fetchRecords () {
try {
sth = con.createStatement();
rs = sth.executeQuery("SELECT * FROM `students`");
while (rs.next()) {
String name = rs.getString("name");
String fname = rs.getString("fname");
String age = rs.getString("age");
String cols[] = {"Name", "Father's Name", "Age"};
String rows[][] = {
{name, fname, age}
};
table = new JTable(rows, cols);
pane.add(new JScrollPane(table));
}
} catch (Exception e) {
System.out.println("An error occured. " + e);
}
}
public static void main (String args[]) {
Test obj = new Test();
obj.connect();
obj.initGUI();
obj.fetchRecords();
}
}