简体   繁体   中英

python sql, “select ? from table where ? like ?”,(selected,where,like))

    select=input("select: ")
    for row in data.execute('select ? from stocks where date like "2015-11-05" ',(select)):

        print(row)

This is is all I'm trying to do right now but I'm getting this error and can't find a solution

    sqlite3.ProgrammingError: Incorrect number of bindings supplied. 
    The current statement uses 1, and there are 5 supplied.

Is there a way to do this? I'm assuming the answer will be similar to the title.

(select) is not a tuple and is a string, a string of 5 characters in your case. Since strings are also iterables, sqlite splits your string into characters and tries to parameterize the query with all of the 5 characters in the string. Instead you meant to have a tuple with a single element inside:

data.execute('select ? from stocks where date like "2015-11-05" ', (select, ))

But, the problem is - this is not going to work, you cannot parameterize the table or column names and you are forced to use string formatting:

data.execute('select {} from stocks where date like "2015-11-05"'.format(select))

Note that, since we are using string formatting here, we are making the code vulnerable to SQL injections - you should definitely validate the select variable value and protect yourself against SQL injections (not sure who would be the user of the program in your case though).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM