Ghias
Ghias

Reputation: 133

JTable not being populated from resultset with DButils

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 */

 }
}
 }                              

Upvotes: 1

Views: 2925

Answers (1)

Rahal Danthanarayana
Rahal Danthanarayana

Reputation: 748

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

Upvotes: 2

Related Questions