开发者

How to change a value in mysql database using conditions from java code?

开发者 https://www.devze.com 2023-03-14 05:36 出处:网络
I\'m trying to change a value Dr_status that only contain one int even 0 or 1. So if Dr_status equal to 1 change it to 0 and vice versa.

I'm trying to change a value Dr_status that only contain one int even 0 or 1. So if Dr_status equal to 1 change it to 0 and vice versa. Here is the code :

String query = "Select Bluetooth_Address FROM dr";
String str = "40D32DBBE6开发者_JAVA技巧65";//in the database I have only two fields in `Bluetooth_Address` column 40D32DBBE665 and another value 
String check = "";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
PreparedStatement preparedStmt= con.prepareStatement("update `dr` set `Dr_status` = '1'");
PreparedStatement preparedStmt1= con.prepareStatement("update `dr` set `Dr_status` = '0'");

  dbtime = rs.getString(1);               
   if (dbtime.equals(str)){
       check = "Select `Dr_status` From `dr` Where `Bluetooth_Address` = " + " " + str ;
       if(check.equals(0)){ 
            preparedStmt.executeUpdate();
                    }
                    if(check.equals(1)){
                        preparedStmt1.executeUpdate();
                    } 

I don't know where is the problem !!! please help. Thanks in advance.


I give +1 to the answer from @Marcelo Hernández Rishmawy. Instead of testing the condition in Java code, do the test and the update in an SQL expression that converts 0 to 1 and 1 to 0 automatically, for the rows that match your Bluetooth address condition.

I'll also give you a tip that in MySQL, 1 and 0 are integers, but they are also used for true and false. So you can use either of the following tricks to make the statement more compact:

"update `dr` set `Dr_status` = ! `Dr_status` where `Bluetooth_Address = " + str

This trick works too:

"update `dr` set `Dr_status` = 1 - `Dr_status` where `Bluetooth_Address = " + str

It's a nice way to simplify, but FWIW it's specific to MySQL, not standard SQL. Other databases brands use proper boolean values, not 1 and 0.


Re your comment: the error is not related to the solutions above, it's because you're interpolating a string of hex digits. You need to either quote the string, or better yet use a query parameter.

You should learn how to use query parameters in any case, because they're good for writing secure code to defend against SQL injection issues, and it's generally easier and more robust than trying to interpolate variables into SQL query strings.

See Using Prepared Statements at The Java Tutorials.


Use something similar to:

"update `dr` set `Dr_status` = CASE `Dr_status` WHEN '1' THEN '0' ELSE '1' END CASE Where `Bluetooth_Address` = '" + str + "'"


The line if(check.equals(0)){ is invalid. check is a String and will never equal 0

0

精彩评论

暂无评论...
验证码 换一张
取 消