0

我的代码工作正常,但是当我尝试运行代码时,它首先显示 java.sql.SQLException:After 结果集结束。我想知道是什么原因造成的,以及如何解决这个问题,因为这是一个分级项目。

public GenerateBill() 
{
    initComponents();
    try 
  {
        Class.forName("java.sql.DriverManager");
        Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore","root","root");
        Statement stmt=(Statement)con.createStatement();
        String query, product;
        query="select * from store;";
        ResultSet rs=stmt.executeQuery(query);
        while(rs.next());
        {
            product=rs.getString("productname");
            jComboBox1.addItem(product);
        }
  } 
    catch(Exception e) 
  {
    JOptionPane.showMessageDialog(null,e.toString());
  }
}

当我执行代码时,首先出现一个消息对话框。当我单击“确定”时,我尝试创建的页面将打开并正常执行。所以,我很困惑这意味着什么。另外,我是这个网站的新手,所以我真的不知道我需要添加多少代码。其余代码用于不同的 jButton。该页面用于生成账单/收据。

4

1 回答 1

0

您的代码中有一些部分可能会更好。具体来说,

  1. 使用com.mysql.jdbc.Driver你的数据库是 MySQL,而不是java.sql.DriverManager

  2. 无需转换您的 Connection 对象。

  3. /bookstore你可以添加之后?useSSL=false,虽然它不是强制性的,所以像jdbc:mysql://localhost:3306/bookstore?useSSL=false

  4. 使用java.sql.PreparedStatement而不是简单地使用Statement.

  5. finally捕获后在一个块中关闭您的连接。

最终,您的代码应该如下所示,

public GenerateBill() {

    initComponents();

    Connection con = null;
    ResultSet rs = null;
    PreparedStatement stmt = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?useSSL=false","root","root");

        String query = "select * from store";
        stmt = con.prepareStatement(query);

        String product;

        rs = stmt.executeQuery();

        while(rs.next())
        {
            product = rs.getString("productname");
            jComboBox1.addItem(product);
        }
  } catch(Exception e) {
        JOptionPane.showMessageDialog(null,e.toString());
  } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
            LOG.error("Error closing the connection with the database...");
            e.printStackTrace();
        }
  }
}

试试上面的,让我知道它是否可以。如果没有,请发布整个异常以查看导致问题的原因。

于 2019-11-07T16:35:40.307 回答