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