When I am trying retrieve values into a JTable
it says "cast connectdb to connection", on the line con=Connect.ConnectDB()
. But I have declared my Connect
class without any error, and are able to insert values from another form successfully. This is my code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
con= Connect.ConnectDB();
String sql="select * from pharmacy";
pst = con.prepareStatement(sql);
pst.execute();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
JOptionPane.showMessageDialog(this,"Succesfully stored","User",JOptionPane.INFORMATION_MESSAGE);
} catch(SQLException ex){
JOptionPane.showMessageDialog(this,ex);
}
}
This is my Connect
class:
public class Connect {
Connection con=null;
public static Connection ConnectDB(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hms_db1","root","root");
return con;
}catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
This is the line you're getting NullPointerException from.. because rs is null
change this line
pst.execute();
to
rs = pst.executeQuery();
You haven't assigned the result from the executeQuery() to the resultSet reference!! and since you're passing a null reference thats why you're getting a NPE. Hope this answers your question.
try pst.executeQuery()
in place of pst.execute()
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
con = Connect.ConnectDB();
String sql = "select * from pharmacy";
pst = con.prepareStatement(sql);
pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
JOptionPane.showMessageDialog(this, "
Succesfully stored" , "User", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, ex);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.