0

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

Wearybands
  • 2,438
  • 8
  • 34
  • 53
  • There's nothing Spring about this, it's just basic JDBC. A really bad example on what not to do. Always use `PreparedStatement` instead of `Statement`. – Kayaman Apr 12 '18 at 13:11
  • maybe you need to add '(quotes) after = in sql query. maybe use prepared statement and set parameters with it if you don't want to deal with it.. – Avinash Anand Apr 12 '18 at 13:12
  • 1
    Seriously??? *NEVER CONCATENATE SQL STATEMENTS*! Read up on SQL-injection. Use prepared statements. – Daniele Torino Apr 12 '18 at 13:15

2 Answers2

1

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'
//------------------^_____^
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

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

mrdc
  • 93
  • 5