JDBC prepareStatement doesn't work

前端 未结 4 1404
北恋
北恋 2020-12-07 06:08

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 va

相关标签:
4条回答
  • 2020-12-07 06:27

    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

    0 讨论(0)
  • 2020-12-07 06:30

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

    0 讨论(0)
  • 2020-12-07 06:30

    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.

    0 讨论(0)
  • 2020-12-07 06:31

    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 = ?
    
    0 讨论(0)
提交回复
热议问题