无法获取类别ID(java / sql)

时间:2014-03-21 10:05:45

标签: java sql resultset

我有2张桌子: salon_stock 类

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

分类表有2列cat_id&标题

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

    private void AddStock() throws 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列。

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

1 个答案:

答案 0 :(得分:1)

查询中的空格可能是错误:

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

必须是

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