java.sql.SQLException:找不到列'Max(category_id'

时间:2019-12-05 01:55:54

标签: java exception

这是我的代码。它给了我一个异常错误,内容为“ java.sql.SQLException:列'Max(category_id')未找到。”。请提供帮助。在此先感谢。

在此处输入代码

公共类Category扩展了javax.swing.JFrame {

/**
 * Creates new form Category
 */
public Category() {
    initComponents();
    DisplayTable();
    autoID();
}


//Display Table
private void DisplayTable() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
        String sql = "SELECT * FROM category";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel(rs));
    }
    catch(Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

public void autoID() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
        Statement s = conn.createStatement();

        ResultSet rs = s.executeQuery("SELECT Max(category_id) from category");
        rs.next();

        rs.getString("Max(category_id)");

        if(rs.getString("Max(category_id") == null) {
            CategoryIDField.setText("C0001");
        }
        else {
            Long id = Long.parseLong(rs.getString("Max(category_id").substring(2, rs.getString("Max(category_id").length()));
            id++;
            CategoryIDField.setText("C0" + String.format("%03d", id ));
        }
    }
    catch(ClassNotFoundException e) {
        Logger.getLogger(Category.class.getName()).log(Level.SEVERE, null, e);
    }
    catch(SQLException e) {
        Logger.getLogger(Category.class.getName()).log(Level.SEVERE, null, e);
    }
}

3 个答案:

答案 0 :(得分:2)

该列具有默认名称,但与函数名称不同,最简单的选择是全部更改

rs.getString("Max(category_id)");

rs.getString(1);

或者,在查询中命名该列。喜欢,

ResultSet rs = s.executeQuery("SELECT Max(category_id) AS FRED from category");

然后使用

rs.getString("FRED");

例如。最后,如果列属于这些类型,则应该使用getIntgetLong(我怀疑这是因为您使用的是MAX)。

答案 1 :(得分:-1)

我认为这是

    if(rs.getString("Max(category_id") == null) {
        CategoryIDField.setText("C0001")

引号应放在右括号后。

答案 2 :(得分:-1)

使用alisa 从类别中选择Max(category_id)作为xxx