简体   繁体   English

MySql数据库的Java连接问题

[英]Java connectivity issue with MySql database

When I am trying retrieve values into a JTable it says "cast connectdb to connection", on the line con=Connect.ConnectDB() . 当我尝试将值检索到JTable时,在con=Connect.ConnectDB()行上显示“将connectdb转换为连接”。 But I have declared my Connect class without any error, and are able to insert values from another form successfully. 但是我已经声明了Connect类,没有任何错误,并且能够成功插入其他表单中的值。 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: 这是我的Connect类:

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 这是您从中获取NullPointerException的行。因为rsnull

change this line 改变这条线

pst.execute();

to

rs = pst.executeQuery();

You haven't assigned the result from the executeQuery() to the resultSet reference!! 您尚未将来自executeQuery()的结果分配给resultSet引用! and since you're passing a null reference thats why you're getting a NPE. 并且由于传递的是空引用,这就是为什么要获得NPE的原因。 Hope this answers your question. 希望这能回答您的问题。

try pst.executeQuery() in place of pst.execute() 尝试使用pst.executeQuery()代替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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM