1

I've been trying to get a handle on how to populate a jtable with data from my resultset and have found out that using DBUtils is probably the easiest method but unfortunately its not working for me at all. The program runs but the jtable remains empty as ever. I don't understand where I'm going wrong with it. I have import net.proteanit.sql.DbUtils; imported at the top and the jar added in class path. Here is my code:

private void jPanel3FocusGained(java.awt.event.FocusEvent evt) {                                    

    // TODO add your handling code here:

    // JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
String DB_URL = "jdbc:mysql://localhost/new";

//  Database credentials
String USER = "root";
String PASS = "";

Connection conn = null;
PreparedStatement stmt = null;
try{
  //STEP 2: Register JDBC driver
   Class.forName("com.mysql.jdbc.Driver");

  //STEP 3: Open a connection
  System.out.println("Connecting to database...");
  conn = DriverManager.getConnection(DB_URL,USER,PASS);

  //STEP 4: Execute a query
  System.out.println("Creating statement...");
  String sql;
  sql = "SELECT * FROM user";
  stmt = conn.prepareStatement(sql);
  //Bind values into the parameters.
  ResultSet rs = stmt.executeQuery();

  jTable1.setModel(DbUtils.resultSetToTableModel(rs));
 }
    catch (SQLException ex) {

 JOptionPane.showMessageDialog(null, ex);
 }
catch(Exception e){
  //Handle errors for Class.forName
  e.printStackTrace();
 }


finally {

try {

  stmt.close();
  conn.close();

} 
catch (SQLException e) { /* ignore */

}



try {

    conn.close();

} catch (SQLException e) { /* ignore */

 }
}
 }                              
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ghias
  • 133
  • 3
  • 18
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). 2) Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow. – Andrew Thompson Jun 08 '14 at 10:04
  • Dang I got it working. Apparently there was nothing wrong with the code but the Action event FocusGained was not working for some reason. Used a button press action event and the same code worked. Strange. – Ghias Jun 08 '14 at 11:14

1 Answers1

2

I got stucked on the same point, So I used "Vectors"

We all know using Arraylist is much better approach when considering the implementations of Vectors.But when working with jTables, by default you got some easy methods to mange the data flow and fill into the jTable which will ease the coding. So if you have less experiance in coding these scenarios like me, I suggest to use Vectors.

Just have to import this and bit of code.

import java.util.Vector;

To learn, how to use Vectors to work with ResultSet refer this

Community
  • 1
  • 1
Rahal Kanishka
  • 720
  • 13
  • 27