-2

I am executing an update and I want to insert the value that is returned from my getter into the my table.

statement.executeUpdate("INSERT INTO my_table " +
          "VALUES(myClass.getValue(), 'abcd',now())");

I have tried debugging through and I found that the String value and datetime executes correctly. However it gives me an exception when I am calling my getter. The detail message that it shows is FUNCTION myClass.getValue does not exist.

My imports are in order. Any ideas?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
sidds224
  • 167
  • 1
  • 1
  • 6

4 Answers4

3
statement.executeUpdate("INSERT INTO my_table " + "VALUES("+myClass.getValue() + ", 'abcd',now())");

Your get-call was interpreted as a String because of the missing ' " '. Take a look at prepared statements, they are easy to read and use and you don't have to struggle with these problems.

Prepared Statement Version (also a lot more secure because they are preventing SQL Injection):

PreparedStatement pst = yourconnection.prepareStatement("INSERT INTO my_table VALUES(?,?,now())";
pst.setString(1,myClass.getValue());
pst.setString(2,"abcd");
pst.executeUpdate();
Community
  • 1
  • 1
Xyaren
  • 955
  • 10
  • 19
1

This is the SQL that you're trying to execute.

INSERT INTO my_table VALUES(myClass.getValue(), 'abcd',now())

You need to pass valid SQL to the executeUpdate method in order for it to run. Java won't interpolate variables and method calls inside strings for you. You have to either concatenate their values into the SQL string that you pass to executeUpdate, or use Prepared Statements instead.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

You need to make a method call to your myClass object, not a string. The string will not be executed, its not code, just words.

statement.executeUpdate("INSERT INTO my_table VALUES(" + myClass.getValue() + ", 'abcd',now())");
Thomas Uhrig
  • 30,811
  • 12
  • 60
  • 80
0

I'm going to show you how to do it with prepared statements since the other answers did not show you:

PreparedStatement prepStmt = con.prepareStatement("INSERT INTO my_table VALUES( ? , 'abcd',now())"));
prepStmt.setString(1, myClass.getValue());
prepStmt.executeUpdate();

Notice the ?. It will get replaced by your Java call to myClass.getValue().

Please do not concatenate SQL strings.

Adam Gent
  • 47,843
  • 23
  • 153
  • 203