I'm receiving the error: sqlite3.OperationalError: near "%": syntax error
when I try to run the following code. import sqlite3
def getFromDB(DBname,table, url):
conn = sqlite3.connect(DBname)
cursor = conn.cursor()
sql = '''SELECT * FROM %s WHERE URL=%s'''
stuff = cursor.execute(sql, (table,url))
stuff = stuff.fetchall()
return stuff
url = 'http://www.examplesite.com/'
getFromDB('AuthorData.sqlite','forbes',url)
I'm using parameters in my SQL
query using %s
. Thanks for the help!
Some idea: - Using parameter is not available for table name - Using string format is not good because of sql-injection
So first, create a method to make table name safe:
def escape_table_name(table):
return '"%s"'.format(table.replace('"', '')
Then complete the code with escape table name and parameter using ?
for parameter:
sql = '''SELECT * FROM %s WHERE URL=?'''.format(escape_table_name(table))
stuff = cursor.execute(sql, (url,))
stuff = stuff.fetchall()
您可以使用:
sql = '''SELECT * FROM {0} WHERE URL= {1}'''.format(table, url)
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.