I'm trying to use the prepareStatement
function. The code is below. After it executes, it returns me a bunch of vlicense
strings instead of the values.
When the code finishing the statement.setString()
, the statement becomes:
select 'vlicense' from Vehicle
However, it needs to be:
select vlicense from Vehicle
without the quotation marks. Can anyone tell me what's the problem?
statement = oConnection.prepareStatement("select ? from Vehicle");
String tempString = "vlicense";
statement.setString(1, tempString);
resultSet = statement.executeQuery();
You can't use parameter markers for column names, table names, data type names, or basically anything that isn't data.
The ? can't be used to specify the fields, just to do some filters in your query like:
In your case your query is built as:
which means: GET ME A STRING 'vlicense' FOR EACH RECORD OF 'Vehicle'. And you'll get n repeated strings depending on the number of records in your table
When you add a bind variable to a statement like this it is escaped, so that actual SQL string in your example would go to the database as "SELECT 'vlicense' FROM Vehicle', selecting a literal string instead of the column name you want.
You need to concatenate that variable column name into your SQL statement before you prepare it:
Bind variables are really for query parameters as opposed to dynamic queries.
It has nothing to do with
jdbc
,prepared-statements
ormysql
.It's just a wrong
sql
statement.If you type:
and the table contains 4 lines, you will get 4 times
as result.
You did not specify your the table structure, but I guess the statement should somehow look like this: