Question

I have 2 tables: salon_stock categories

the salon_stock table has a fk column cat_id of categories table

Categories table have 2 columns cat_id & title

In the below code i am trying to insert the cat_id which belong to a category name retrieved from a JComboBox along with the data of salon_stock table

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

the code runs fine but in the table, it inserts the '0' value to the cat_id column of stock_table.

i am unable to detect the error.. please help me..

Was it helpful?

Solution

maybe the space in the query is the error:

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

must be

"select * from categories where title='"+cat+"'"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top