ResultSet rs = stat.executeQuery("select * from donor where username = '" + username + "'");
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
System.out.println(Updatesentence);
stat.executeUpdate(Updatesentence);
Guys I am trying to make an update to an SQL database with this code and although I am not getting an error somewhere the code does not work with the desired result. The
System.out.println(Updatesentence);
is not printed and the update is not performed. I know there probably is somewhat of a syntax error on my String declaration, but I cannot work it out.
You have this:
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
So if the user's blood type is AB...
update bank set AB = AB + 1 where name = 'JohnSmith'
And that obviously won't work. You need to indicate the column in the database you want to be updating.
One of the most important things you need to remember when writing SQL statements, is to separate the query literal from the query arguments. This allows protection from SQL Injection and also makes it possible for the DB to reuse the query with different arguments (and "hard parsing" / optimizing the query only once). The way you do this with JDBC, is through prepared statements:
try (PreparedStatement queryPS = myConnection.prepareStatement(
"select * from donor where username = ?");
PreparedStatement updatePS = myConnection.prepareStatement(
"update bank set bloodtype = ? where name = ?");) {
queryPS.setString(1, username);
ResultSet rs = queryPS.executeQuery();
if (rs.next()) {
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
updatePS.setString(1, type);
updatePS.setString(2, username);
updatePS.executeUpdate();
}
} catch (SQLException e) {
// handle it
}
When you use prepared statements, you don't need to worry about concatenating the inputs into the query; they will be sanitized and injected automatically. If you're doing things the "wrong way", it's really easy to make a mistake when you construct the query piece by piece from different variables in your code, and this is exactly what happened with the misplaced type variable in your example.
Your update statement is wrong. It should be :
String Updatesentence = "update bank set bloodtype = " + type + " + 1 where name = '" + name + "'" ;
Related
I'm trying to make CRUD (Create, Read, Update, Delete) to my projects. But it seems the "update" doesn't work. It keeps saying
java.sql.SQLSyntaxErrorException : You have an error in your SQL syntax; check the manual that coresponds to your MariaDB server version for the right syntax to use near "Number" = 0813874810 WHERE Name = "Gregory" at line 1)
What the solution for this?
Here is my code:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata", "root", "");
String sql = "UPDATE employeetab SET Name = '" + txtEmployeeName.getText()
+ "',Address = '" + txtEmployeeAddress.getText()
+ "',Gender = '" + gender_type
+ "',Phone Number = '" + txtEmployeePhone.getText()
+ "' WHERE Name = '" + txtEmployeeName.getText() + "'";
stm = conn.prepareStatement(sql);
stm.execute(sql);
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
Problem comes from the space in column Phone Number. To make it work you need to escape the column name with `.
UPDATE employeetab
SET Name = 'something',Address = 'some address',Gender = 'whatever',`Phone Number` = '000000000'
WHERE Name = 'something';
You should follow sql naming conventions, normally words in column names are separated by _. Your column name should be - phone_number.
Also, as mentioned in comments, you should not just add user input into sql queries, because you are leaving yourself wide open for sql injection.
You need to follow the naming conventions , their is space between 'Phone Number' column you should not write like this you need to add _ in between of this two.
try this :
String gender_type = null;
if (ButtonM.isSelected()){
gender_type = "Male";
}else if(ButtonFM.isSelected()){
gender_type = "Female";
}
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata","root","");
String sql = "UPDATE employeetab SET Name = ? ," +
" Address = ? ," +
" Gender = ? ," +
" Phone Number = ? ," +
" WHERE Name = ? ," ;
PreparedStatement pStmt = conn.prepareCall(sql);
pStmt.setString(1, txtEmployeeName.getText()+"");
pStmt.setString(2, txtEmployeeAddress.getText()+"");
pStmt.setString(3, gender_type+"");
pStmt.setString(4, txtEmployeePhone.getText()+"");
pStmt.setString(5, txtEmployeeName.getText());
pStmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
its cleaner and should work.
I am making a program using Eclipse that allows the user to update the volume of chemicals everytime they’re restocked/used, which requires them to enter the ID of the chemical and the amount they would like to add/subtract. A query is then performed to search for the chemical's ID in the database, and its volume is updated accordingly.
However, I’m having difficulties getting the volume to update. I tried adapting MySQL’s UPDATE statement from this website to SET volume = volume + amount added, WHERE chemical ID = ID entered by the user; however, there appears to be some syntax errors in my code, more specifically at the UPDATE - SET - WHERE line:
public void IDEnter() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8889/StockControlSystem","root","root");
Statement stmt = con.createStatement();
String sql = "Select * from Chemicals where `Chemical ID` ='" + txtChemical_ID.getText()+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
stmt.executeUpdate("UPDATE Chemicals" + "SET `Volume` = rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText()) WHERE `Chemical ID` in (txtChemical_ID.getText())");
}
else {
JOptionPane.showMessageDialog(null, "Invalid chemical ID");
txtChemical_ID.setText(null);
}
} catch(Exception exc) {
exc.printStackTrace();
}
}
Since I'm still new to MySQL, can someone help me correct this? Thank you so much for your help!
Your whole query is badly formatted. Change your code to this:
stmt.executeUpdate("UPDATE Chemicals SET Volume = " +
rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText())
+ " WHERE Chemical_ID in (" + txtChemical_ID.getText() + ")");
You cannot use ' single quotes when defining Column names in queries. Single quotes are used for string values!
Still, this would not be the best way to do this. use PreparedStatement!
This way:
String updateString = "UPDATE Chemicals SET Volume = ? WHERE Chemical_ID in (?)"; // Creation of the prepared statement, the ? are used as placeholders for the values
PreparedStatement preparedStatement = con.prepareStatement(updateString);
preparedStatement.setInt(1, rs.getInt(Volume) + Integer.parseInt(AmountAdded.getText())); // Setting the first value
preparedStatement.setString(2, txtChemical_ID.getText()); // Setting the second. I am supposing that this txtChemical_ID textField has values seperated by commas, else this will not work!
preparedStatement.executeUpdate();
If you need to read more for PreparedStatement there are a lot of great resources out there. They also protect against SQL injections.
I think your problem might be with the "rs.getInt(Volume)"
Yours:
"UPDATE Chemicals" + "SET `Volume` = rs.getInt(Volume)
+ Integer.parseInt(AmountAdded.getText())
WHERE `Chemical ID` in (txtChemical_ID.getText())"
Can you try this:
"UPDATE Chemicals" + "SET `Volume` = " +
Integer.parseInt(AmountAdded.getText()) + "
WHERE `Chemical ID` in (" + (txtChemical_ID.getText()) +")"
I am making a program without knowing much about programming... I used some youtube videos to help me.
My program is made for a chef that can edit users & food and gather ratings and suggestions from the inspector. The chef's section of editing users' details works.
However, the inspector's rating does not as it throws an error: SQLSyntaxException: Encountered "Vegetarian" at line 1, column 65. I believe it is because of getting the rating value (which is int) in a wrong way...
'
public void getConnection(){
try{
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1327/MyApp", "Me", "Me");
mystatObj=myconObj.createStatement();
myresObj=mystatObj.executeQuery("Select * from Me.Food");
tableRateFood.setModel(DbUtils.resultSetToTableModel(myresObj));
}
catch (SQLException e){
e.printStackTrace();
}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "update Me.Food set Name = '" + nameText.getText()
+ "',Type = '" + typeText.getText()
+ "', Rating = '" + ratingText.getText()
+ ", 'Vegetarian = '" + vegetarianText.getText()
+ "', ShownOnMenu = '" + showText.getText()
+ "' where Id = " + idText.getText();
//tried the following... did not work either
/*+ " Rating = " + Integer.parseInt(ratingText.getText()));*/
Statement update= myconObj.createStatement();
update.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Updated successfully!");
}
catch(SQLException E){
E.printStackTrace();
}
getConnection();
}
Your forgot a quote in ", 'Vegetarian = '"
Talking about building query strings, you should avoid +-ing values and rely on prepared statements with sql parameters instead. Allows the database to cache the query and avoids sql injection attacks. And spares you formatting headache, think about date values.
I have the following code:
try {
userPasswordNew = new String(ChangePW.passwordFieldconfirm.getPassword());
PreparedStatement prepStmt = connection.prepareStatement(
"UPDATE " + TABLE_NAME + " SET password = " + userPasswordNew + " WHERE username = " + username);
prepStmt.setString(2, BCrypt.hashpw(userPasswordNew, BCrypt.gensalt(bcryptRounds))); //2 represents number of column in database starting with 0
System.out.println(prepStmt);
return prepStmt.executeUpdate() != 0;
} catch (SQLException e) {
e.printStackTrace();
}
I tried 1 2 and 3 as indexes but everytime it throws an Index out of range exception. Is there another way to get the column, maybe adressed with its name? Or what am I doing wrong?
Could somebody please help?
To use prepared statements - please use ? instead provided values. Like in this sample:
String updateString =
"update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
updateSales = con.prepareStatement(updateString);
To get more, please look here. In your case that could be:
PreparedStatement prepStmt = connection.prepareStatement(
"UPDATE " + TABLE_NAME + " SET password = ? WHERE username = ?");
prepStmt.setString(1, "that new password");
prepStmt.setString(2, "user_name");
I assume password and username are textual values. Hence you will have to enclose the values by quotes.
That is the query will be
"UPDATE " + TABLE_NAME + " SET password = " + userPasswordNew + " WHERE username = " + username
Also, as you are using PreparedStatement, you must not mention the variables in the query. A neater approach would be to use ? instead. Something like this.
"UPDATE " + TABLE_NAME + " SET password = ? WHERE username = ?
And then use .setString() etc methods with userPasswordNew and username.
Check this, https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
When you use PreparedStatement, you define the parameters to pass in the sql statement by placing 1 or more ?.
Then you pass values to these parameters with methods like setString(), setInt(),... The order of the parameters is not 0 based but 1 based.
try {
userPasswordNew = new String(ChangePW.passwordFieldconfirm.getPassword());
PreparedStatement prepStmt =
connection.prepareStatement("UPDATE " + TABLE_NAME +" SET password = ? WHERE username = ?");
prepStmt.setString(1, userPasswordNew);
prepStmt.setString(2, username);
System.out.println(prepStmt);
return prepStmt.executeUpdate() != 0;
} catch (SQLException e) {
e.printStackTrace();
}
In your code there is this line:
prepStmt.setString(2, BCrypt.hashpw(userPasswordNew, BCrypt.gensalt(bcryptRounds)));
I don't know if this is a parameter that you want to pass.
If it is I can't see a ? placeholder in the sql statement.
I'm coding some database transactions by using java. I'm sending a query using java. I think it has no problem with it. And if I send the query at prompt, it is working.
This method is updating book quantity.
private static void updateBquantity(int bqt, String bname) {
Connection con = makeConnection();
try {
Statement stmt = con.createStatement();
System.out.println(bqt + " " +bname);
//this part is making problem
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where bookname = '" + bname + "';");
System.out.println("<book quantity updated>");
} catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where 도서이름 = '" + bname + "';");
This part is making problem.
Other queries using this form is working.
The compiler says :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'bookname = 'Davinci Code'' at line 1
Help me.
I'm confused with bookname = 'Davinci Code, where is bookname in your query? No matter what, in this query, you missed a blank before where, try this:
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + " where 도서이름 = '" + bname + "';");