3

Hi I have successfully linked my jTable to JDBC database. However, I am having trouble retrieving them. I want the saved data to appear when I restart the program but it is not working.

alarm.setText("");  
    DefaultTableModel model =(DefaultTableModel) hwList.getModel();
    if(!className.getText().trim().equals(""))
    {
        model.addRow(new Object[]{className.getText(), homeWork.getText(), dueDate.getText()});
    }
    else
    {
        alarm.setText("Class Name should not be blank.");
    }

        Connection conn;
        Statement st;

        try
    {
        String myDriver = "com.mysql.jdbc.Driver";
        String myUrl = "jdbc:mysql://localhost:3306/mysql";
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Connecting to database");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
        System.out.println("Connected to databse");


        String a = className.getText();
        String b = homeWork.getText();
        String c = dueDate.getText();            

        System.out.println("Inserting into the table");
        st = conn.createStatement();
        String stmt="INSERT INTO hwList (className, homeWork, dueDate)"+ "VALUES ("+"\'"+a+"\',"+"\'"+b+"\',"+"\'"+c+"\')";
        System.out.println(stmt);
        st.executeUpdate(stmt);

        System.out.println("Saved!");

    }
    catch (Exception e)
    {
        System.err.println("Got an exception!");
        System.err.println(e.getMessage());
    }    

This is my code for saving the document!

Is there any way to retrieve data in JDBC data base and show it through Jtable? I'm so sorry for asking such a simple question but I am new to java and I desperately need help!

Thank you so much!

Code used to load the data...

Btw, my jtable is a 3 column table with three columns--className, homeWork, dueDate respectively. Thank you!

String sql="SELECT * FROM hwList";
ResultSet rs = st.executeQuery(sql);
while(rs.next())
{
    String d = rs.getString("className");
    String e = rs.getString("homeWork");
    String f = rs.getString("dueDate");
}
4
  • Where's you select statement, where you load the new data? Commented Jan 7, 2015 at 9:44
  • sorry. I'm new to the website and I just couldnt find my original post. What do you mean create an instance variable? Thank you! Commented Jan 7, 2015 at 10:28
  • i mean what does "You need to take this and update your original question, but basically, you need to create an instance of the TableModel and put each row of data into the model.." this mean? create an instance of the TableModel? Commented Jan 7, 2015 at 10:29
  • 1
    DefaultTableModel model = new DefaultTabelModel(); creates a new instance of the DefaultTableModel class Commented Jan 7, 2015 at 10:32

6 Answers 6

18

Start by creating a new TableModel...

DefaultTableModel model = new DefaultTableModel(new String[]{"Class Name", "Home work", "Due Date"}, 0);

Load the data from the database...

String sql="SELECT * FROM hwList";
ResultSet rs = st.executeQuery(sql);

Add each row of data to the table model...

while(rs.next())
{
    String d = rs.getString("className");
    String e = rs.getString("homeWork");
    String f = rs.getString("dueDate");
    model.addRow(new Object[]{d, e, f});
}

Apply the model to your JTable...

table.setModel(model);

You may also want to look at The try-with-resources Statement and make sure you're managing your resources properly

Sign up to request clarification or add additional context in comments.

Comments

2

Step:1

import javax.swing.*;
import java.awt.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
public class UserList extends JFrame {
    DefaultTableModel model = new DefaultTableModel();
    Container cnt = this.getContentPane();
    JTable jtbl = new JTable(model);
    public UserList() {
        cnt.setLayout(new FlowLayout(FlowLayout.LEFT));
        model.addColumn("Id");
        model.addColumn("Username");
        model.addColumn("Password");
        model.addColumn("Create");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/java_db", "root", "");
            PreparedStatement pstm = con.prepareStatement("SELECT * FROM users");
            ResultSet Rs = pstm.executeQuery();
            while(Rs.next()){
                model.addRow(new Object[]{Rs.getInt(1), Rs.getString(2),Rs.getString(3),Rs.getString(4)});
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        JScrollPane pg = new JScrollPane(jtbl);
        cnt.add(pg);
        this.pack();
    }
}

Step:2

import javax.swing.JFrame;
public class Main {
    public static void main(String[] args) {
        JFrame frame = new UserList();
        frame.setTitle("Swing Example");
        frame.setSize(500, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Demo

enter image description here

1 Comment

Don't Forget Add JDBC Driver
1
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/mysql";
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
System.out.println("Connected to databse");
Statement st;
Vector data = new Vector();
try {
    st = connection.createStatement();
    ResultSet res = st.executeQuery("SELECT col_name FROM table_name");
    ResultSetMetaData metaData = res.getMetaData();
    int columns = metaData.getColumnCount();
    while (res.next()) {
       Vector row = new Vector(columns);
       for (int i = 1; i <= columns; i++) {
        row.addElement(res.getObject(i));
       }
       data.addElement(row);
    }
} catch (SQLException e) {
    e.printStackTrace();
}
Vector columnNames = new Vector();
columnNames.addElement("col_1");
columnNames.addElement("col_name_n");
table = new JTable(data,columnNames);

You can use something like the code above to retrieve data from database and store it in jtable.

1 Comment

table = new JTable(data,columnNames); is not required unless you've never built the table before. Simply create the new model and apply to an existing instance of JTable...
0

Hie,

  1. Change yourResultSet to an ArrayList
  2. Create a model for your JTalbe that uses data from the ArrayList

That should work.

2 Comments

How is that loading data from the database?
"Is there any way to retrieve data in JDBC data base and show it through Jtable?"...
0

First create the table model then use that fetch_data() function. Make sure your database connection is working. Call the function in main constructor. That's it.

DefaultTableModel dm;

dm=(DefaultTableModel) jTable1.getModel();

public void fetch_data(){

    try{
        String sql= "select * from tbl_name";
        ResultSet rs=st.executeQuery(sql);
        YourjTableName.setModel(DbUtils.resultSetToTableModel(rs));
    }catch(Exception e){
        System.out.println(e);
    }
}

Comments

0

Problem Statement : Retrive data from database and display on JTable in java.

CODE: (for retrieve) *change code according to your need

String tquery = "SELECT * FROM Member";
        DbConnection obj = new DbConnection();
        ResultSet r = obj.Retrive(tquery);
        while (r.next()) {
            int i = r.getInt(1);
            String d = r.getString(2);
            String e = r.getString(3);
            String f = r.getString(4);
            String h = r.getString(5);
            String w = r.getString(6);
            DefaultTableModel model = (DefaultTableModel) (Member_table.getModel());
            model.addRow(new Object[]{i, d, e, f, h, w});
        }

CODE (simplified):

        String tquery = "SELECT * FROM Member";
        ResultSet rs = st.executeQuery(sql);
        while (r.next()) {
            int i = r.getInt(1);
            String d = r.getString(2);
            DefaultTableModel model = (DefaultTableModel) (Member_table.getModel());
            model.addRow(new Object[]{i, d);//add row to JTable
        }

if thisDefaultTableModel model = new DefaultTableModel(); not work use DefaultTableModel model = (DefaultTableModel) (Member_table.getModel());

Hope it helps you!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.