how would i write this sql statement without a hard coded value?
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name = 'john'");
// this works
rather have something like:
String name = "john";
resultSet = statement
.executeQuery("select * from myDatabase.myTable where name =" + name);
// Unknown column 'john' in 'where clause' at
// sun.reflect.NativeConstructorAccessorImpl.newInstance0...etc...
thanks in advance..
Put quotes around your
name
value since it's a string.It is generally a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
Note that
prepareStatement()
is an expensive call (unless your application server uses statement caching and other similar facilities). Theoretically, it'd be best if you prepare the statement once, and then reuse it multiple times (though not concurrently):you need to put quotes around the value ('john' instead of john)...
Try the following :
this should work:
You are missing the single quotes around your string, your code corrected:
Print out / log text of the query before executing the query to see if it looks OK.
If you are going to do a lot of similar queries where only the constant changes, consider using prepared statements