简体   繁体   中英

How do I retrieve a single cell from MySQL database using query and assigned it to a variable in Java Netbeans Apache

First I am going to try using query to retrieve the int min_stock single cell using the item description. Then put that value into a variable. I want to be able to have the variable minStock to be equal to a number. I want to use it to make operations in my program.

PreparedStatement cm = con.prepareStatement(checkMinimumStock);
ResultSet minS = cm.executeQuery("SELECT min_stock FROM items WHERE item_description = '"+item+"'"); 
            int minStock = minS.getInt("min_stock");```

you are choose wrong way to use PrepareStatment .
you have two option to do:

1:
String sql = "SELECT min_stock FROM items WHERE item_description =?";
PreparedStatement cm = con.prepareStatement(sql);
cm.setString(1, item);
ResultSet rs = cm.executeQuery();

2:
String sql = "SELECT min_stock FROM items WHERE item_description = '" + item + "'";
ResultSet rs = con.createStatement().executeQuery(sql);

and then

if (rs.next())
int minStock = rs.getInt("min_stock");
else
//not found any match row in DB table

Try this

String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description = ? ";
PreparedStatement cm = con.prepareStatement(checkMinimumStock);
cm.setString(1,item);
ResultSet minS = cm.executeQuery();
if(minS.next()){
  int minStock = rs.getInt("min_stock");
}

String checkMinimumStock = "SELECT min_stock FROM items WHERE item_description =? ";

Forgot to add this in the beginning of the code!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM