JDBC prepareStatement doesn't work

2020-02-02 03:54发布

问题:

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();

回答1:

You can't use parameter markers for column names, table names, data type names, or basically anything that isn't data.



回答2:

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:

statement = oConnection.prepareStatement("SELECT " + vlicense + " FROM Vehicle");

Bind variables are really for query parameters as opposed to dynamic queries.



回答3:

The ? can't be used to specify the fields, just to do some filters in your query like:

statement = conn.prepareStatement("select field from Vehicle where name=?");

In your case your query is built as:

select 'vlicense' from Vehicle

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



回答4:

It has nothing to do with jdbc, prepared-statements or mysql.
It's just a wrong sql statement.

If you type:

Select 'justanexample' from Vehicle

and the table contains 4 lines, you will get 4 times

'justanexample'
'justanexample'
'justanexample'
'justanexample'

as result.

You did not specify your the table structure, but I guess the statement should somehow look like this:

select * from Vehicle where license = ?