MySql数据库的Java连接问题

时间:2015-01-06 06:14:56

标签: java mysql swing

当我尝试将值检索到JTable时,它表示"将connectdb转换为连接",在行con=Connect.ConnectDB()上。但是我已经声明我的Connect类没有任何错误,并且能够成功地从另一个表单插入值。这是我的代码:

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);
  }
}  

这是我的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;
    }      
  }
}

2 个答案:

答案 0 :(得分:2)

jTable1.setModel(DbUtils.resultSetToTableModel(rs));

这是您从...获取NullPointerException的行...因为 rs null

更改此行

pst.execute();

rs = pst.executeQuery();

您尚未将executeQuery()的结果分配给resultSet参考!!因为你传递了一个空引用,这就是你获得NPE的原因。希望这能回答你的问题。

答案 1 :(得分:0)

尝试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);
    }
}