This question already has answers here:
Difference between Statement and PreparedStatement
(15 answers)
Closed 4 years ago.
I am writing a simple method to update a record using spring jdbc the method is
#Override
public void updateEmployee(Employee e, int id) {
try {
Connection connection = DemoApplicationServiceImpl.getConnection();
Statement statement = connection.createStatement();
String update = "UPDATE salesforce.Employee__c SET First_Name__c = " + e.getFirst() + ", Last_Name__c = "
+ e.getLast() + ", Email__c = " + e.getEmail() + " WHERE Id = " + id;
System.out.println(update);
statement.executeQuery(update);
} catch (Exception ex) {
ex.printStackTrace();
}
}
It gives me an error
psqlexception column "umair" does not exist
umair is not even a column in database
Can anyone help?
Thanks
Your solution can cause SQL Injection or Syntax error, instead use PreparedStatement it is more secure and more helpful :
String update = "UPDATE salesforce.Employee__c SET First_Name__c = ?, Last_Name__c = ?, Email__c = ? WHERE Id = ? ";
try (PreparedStatement pstm = connection.prepareStatement(update)) {
pstm.setString(1, e.getFirst());
pstm.setString(2, e.getLast());
pstm.setString(3, e.getEmail());
pstm.setInt(4, id);
pstm.executeUpdate();
}
About your Error :
You get that error because you try to use something like this :
SET First_Name__c = umair
But String or varchar should be between two quotes :
SET First_Name__c = 'umair'
//------------------^_____^
Try this:
String update = "UPDATE salesforce.Employee__c SET First_Name__c = '" + e.getFirst() + "', Last_Name__c = '"
+ e.getLast() + "', Email__c = '" + e.getEmail() + "' WHERE Id = " + id;
When comparing fields to string values (and other values in general), you need to use quotes, like FIELD = 'Value'.
But as others said, is better to always use PreparedStatement
https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
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.
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: TOP near line 1, column 8 [SELECT TOP 10 IServe.ID FROM TopUp.dbo.IServe WHERE ExpireDate >= '2019-10-03' AND TelcoID = '2' AND ProductID = '2' AND RechargeAmt = '100.0' AND Available = 1 ORDER BY ExpireDate, SN]
String query3 = "SELECT TOP " + importStockList.getOrderQuantity() +" IServe.ID FROM IServe WHERE "
+ " ExpireDate >= '" + sqlDate + "' " + " AND TelcoID = '" + importStockList.getTelcoId()
+ "' AND ProductID = '" + importStockList.getProductId() + "' AND " + "RechargeAmt = '"
+ importStockList.getRechargeAmt() + "' AND Available = 1 ORDER BY ExpireDate, SN" ;
Session hbsessionSQL = HibernateUtilSQL.getSessionFactory().openSession();
List<Iserve> iserve = hbsessionSQL.createQuery(query3).list();
Can you please help me this error. I am stuck here
While your query is hard to read, and you should be using a prepared statement, I don't see anything wrong per se about the syntax. So the error is probably happening because TOP is not valid HQL syntax. TOP is really only supported on Microsoft databases, such as SQL Server or Access. Try using LIMIT instead:
try {
Session session = HibernateUtilSQL.getSessionFactory().openSession();
Connection conn = session.connection();
String sql = "SELECT ID FROM IServe WHERE ExpireDate >= ? AND TelcoID = ? AND ProductID = ? AND RechargeAmt = ? AND Available = 1 ORDER BY ExpireDate, SN LIMIT ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, sqlDate);
ps.setInt(2, importStockList.getTelcoId());
ps.setInt(3, importStockList.getProductId());
ps.setInt(4, importStockList.getRechargeAmt());
ps.setInt(5, importStockList.getOrderQuantity());
ResultSet rs = ps.executeQuery();
while(rs.next()) {
// process result set here
}
}
catch(HibernateException e) {
e.printStackTrace();
}
Since its not understood what type your variables are, try to see the data by yourself. If there is an option string values contain special characters, remove them first.
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.
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 + "'" ;
I'm trying to check if the "Username" and "Email" arguments in my constructor are existed in the SQL Table.
this is my code:
public DB(String usr, String eml, String pwd) {
this.usr = usr;
this.eml = eml;
this.pwd = pwd;
String jdbcUrl = "jdbc:mysql://localhost:3306/registered";
String jdbcUser = "....";
String jdbcPassword = "....";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);
statement = connection.createStatement();
now , if i use SELECT with two columns, like this:
String command = "SELECT UserName,Email FROM users WHERE UserName LIKE '" + this.usr.toString() + "';";
resultSet = statement.executeQuery(command);
and then do my loop for resultSet... like this:
while (resultSet.next()) {
if (usr.equalsIgnoreCase(resultSet.getString("UserName"))) {
System.out.println("UserName : " + this.usr + " is taken!");
}
else if (eml.equalsIgnoreCase(resultSet.getString("Email"))) {
System.out.println("Email : " + this.eml + " is taken!");
}
else {
System.out.println("Email : " + this.eml + " and UserName : " + this.usr + " are AVAILABLE!");
command = "INSERT users SET UserName = '" + this.usr.toString() + "',Email = '" + this.eml.toString() + "',Password = '" + this.pwd.toString() + "',Status = '0' ,Connected = '1';";
statement.executeUpdate(command);
}
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("Vendor error: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
the
resultSet.next()
only runs over the "FIRST" column which means
if the "usr" exists in the table it works,
but if the "usr" does not exist in the table, the other two if statements does-not work ..
,... i want to check both first column and second,.. and maybe third or more soon.. , any help?
Your WHERE clause only tests for the UserName, so if the UserName doesn't match this.usr.toString(), the resultSet will be empty, so the while loop won't be entered.
You should change the query to match all the fields you care about - something like - "SELECT UserName,Email FROM users WHERE UserName = ... OR Email = ..."
If the resultSet is empty, you'll know that you can insert the new record. Otherwise, you can check which of the fields (UserName, Email) is already taken.
One more thing you should be aware of - executing a SQL statement without PreparedStatement makes your code vulnerable to SQL injection attacks.
You should change your code to something like this :
PreparedStatement pstmt = con.prepareStatement("SELECT UserName,Email FROM users WHERE UserName = ? OR Email = ?");
pstmt.setString(1, this.usr);
pstmt.setString(2, this.eml);
resultSet = pstmt.executeQuery();
You should change your INSERT statement similarly to use PreparedStatement.