【问题标题】:can't get the category ID ( java/sql )无法获取类别 ID ( java/sql )
【发布时间】:2014-03-21 10:05:44
【问题描述】:

我有 2 张桌子: 沙龙库存 类别

salon_stock 表有一个类别表的 fk 列 cat_id

类别表有 2 列 cat_id 和标题

在下面的代码中,我试图插入属于类别名称的 cat_id 从 JComboBox 以及 salon_stock 表的数据中检索

 private void AddStock() 抛出 SQLException,NullPointerException {

int catID = 0;

String cat=cat_list.getSelectedItem().toString();

if (cat.equals("Select a Category")) { ResultSet rs = con.createStatement().executeQuery("select * from categories where title=' Default'"); if(rs.next()){ catID=rs.getInt("cat_id"); } else{ throw new SQLException("The 'Default' category was not found in the Categories Table"); } } else{ ResultSet rs = con.createStatement().executeQuery("select * from categories where title=' "+cat+"'"); if(rs.next()){ catID=rs.getInt("cat_id"); } } ps1 = con.prepareStatement("insert into "+tableName+"(title,price,qty,cat_id) values( ?,?,?,?)"); ps1.setString(1,title_field.getText()); ps1.setInt(2,Integer.parseInt(price_field.getText())); ps1.setInt(3,Integer.parseInt(qty_field.getText())); ps1.setInt(4,catID); ps1.executeUpdate(); ps1.closeOnCompletion(); }

代码运行良好,但在表中,它将“0”值插入 stock_table 的 cat_id 列。

我无法检测到错误.. 请帮帮我..

【问题讨论】:

    标签: java sql resultset


    【解决方案1】:

    也许查询中的空格是错误的:

    "select * from categories where title=' "+cat+"'"
    

    必须

    "select * from categories where title='"+cat+"'"
    

    【讨论】:

    • 那么你可以关闭问题
    • 如何关闭它?我应该删除它还是标记它?
    • 在左上角我的答案附近,有一个 V 勾号,鼠标悬停时变为绿色:点击它
    • 我做到了;我很久以前就试过了,但我必须等待至少 8 分钟 .. 无论如何,非常感谢这是我在 stackoverflow 上得到的非常快速的响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多