sqlite3.OperationalError: near "%": syntax error? - python

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

You can use :
sql = '''SELECT * FROM {0} WHERE URL= {1}'''.format(table, url)

Related

How to put db name into query using %s

I have a following sql query:
SELECT *
FROM %s.tableA
The tableA is in db-jablonec so I need to call db-jablonec.tableA.
I use this method in Python:
def my_method(self, expedice):
self.cursor = self.connection.cursor()
query = """
SELECT *
FROM %s.tableA
"""
self.cursor.execute(query, [expedice])
df = pd.DataFrame(self.cursor.fetchall())
I call it like this:
expedice = ["db-jablonec"]
for exp in expedice:
df = db.my_method(exp)
But I got an error MySQLdb.ProgrammingError: (1146, "Table ''db-jablonec'.tableA' doesn't exist")
Obviously, I want to call 'db-jablonec.tableA' not ''db-jablonec'.tableA'. How can I fix it please?
It is passing %s as its own string including the quotes ''
you therefore need to pass it as one variable. Concatenate .table to the variable itself then pass it in.
Your query will therefore then be
query = """
SELECT *
FROM %s
"""
I think this will helpful for you
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%%'
Refer This.

In SQLite, how do I search my database with text from an entry box, and display the result as text?

I have an Entry box on my search page. I want this function to search the table (movies) in my database for whatever text (column name is 'title') was entered into that Entry box, and then display the result.
def search_now():
conn = sqlite3.connect('movie_catalog.db')
c = conn.cursor()
searched = search_box.get()
sql = "SELECT * FROM movies WHERE title = %s"
name = (searched, )
result = c.execute(sql, name)
if not result:
result = "Movie not found"
# Commit our changes
conn.commit()
# Close database connection
conn.close()
I keep getting the following error message:
sqlite3.OperationalError: near "%": syntax error
The tutorial I've been using is using MYSql, so I'm not sure if the "%s" placeholder applies or not. Any ideas?
you should either do this (not safe)
searched = search_box.get()
sql = "SELECT * FROM movies WHERE title = '%s'" % searched
result = c.execute(sql)
or this (fairly secure against injections)
searched = search_box.get()
t = (searched,)
sql = "SELECT * FROM movies WHERE title=?"
result = c.execute(sql, t)
EDIT:
In your example you are passing the literal string SELECT * FROM movies WHERE title = '%s'" to the database, this is why it is complaining about the %s

passing a python variable into a mysql select statement

Hi I have the following block of code that is meant to take the variable 'search_value'and pass it into the WHERE clause of a mysql select statement
import MySQLdb
search_term = input('Enter your search term: ')
print (search_term)
conn = MySQLdb.connect(my connection info)
c = conn.cursor()
q = "SELECT * FROM courses WHERE course_area = %(value)s "
params = {'value': search_term}
c.execute(q, params)
rows = c.fetchall()
for eachRow in rows:
print (eachRow)
I know that I need to use %s somewhere but I'm not sure of the exact syntax. I did some searching online but I have only found examples of insert statement...and I know they have a little different syntax. Thanks
This should work:
q = "SELECT * FROM courses WHERE course_area = %(value)s "
params = {'value':'some_value_here'}
c.execute(q, params)
.....

Error in using variables in SQL statement in Python?

I have the following Python code:
cursor = connection.cursor()
a = "C6DE6778-5956-48D4-BED6-5A2A37BBB123"
SQLCommand = ("""SELECT *
FROM Table
WHERE Table.ENUM = ?
""", a)
results = cursor.execute(SQLCommand)
The following error is returned:
TypeError: string or integer address expected instead of tuple instance
The way you constructed the sqlcommand is incorrect. Pass the parameter when you execute.
a = "C6DE6778-5956-48D4-BED6-5A2A37BBB123"
SQLCommand = """SELECT *
FROM Table
WHERE Table.ENUM = ?
"""
results = cursor.execute(SQLCommand,(a,))
SQLCommand is a tuple in your case. .execute() expects sql statement as the first argument. To rectify the error, you can do something like this :
cursor = connection.cursor()
a = "C6DE6778-5956-48D4-BED6-5A2A37BBB123"
SQLCommand = """SELECT *
FROM Table
WHERE Table.ENUM = '%s'
""" % a
results = cursor.execute(SQLCommand)
Alternatively, you can format you SQL statement string like this :
SQLCommand = """SELECT *
FROM Table
WHERE Table.ENUM = '{}'
""".format(a)
Or you can pass a as an optional parameter to .execute() like this :
cursor = connection.cursor()
a = "C6DE6778-5956-48D4-BED6-5A2A37BBB123"
SQLCommand = """SELECT *
FROM Table
WHERE Table.ENUM = ?
"""
print(SQLCommand, a)
You can refer to the documentation for more understanding on this.

OperationalError when using Python sqlite3 module

def StatusUpdate(self, table):
inventoryCurs.execute('SELECT * from Table')
for i in inventoryCurs:
html = urlopen(i[5]).read()
Soup = BeautifulSoup(html)
if table.StockStatus(Soup) == 'Out of Stock':
inventoryCurs.execute('''UPDATE table SET status = 'Out of Stock' WHERE id = %s)''', i[0])
inventoryCurs.execute('''UPDATE table SET status = 'Out of Stock' WHERE id = %s)''', i[0])
OperationalError: near "%": syntax error
Without seeing more of the code, it's difficult to fix the problem completely, but looking at your code, I think the problem might be the %s in this line:
inventoryCurs.execute('''UPDATE table SET status = 'Out of Stock' WHERE id = %s)''', i[0])
According to the documentation for the SQLite module in both Python 2 and Python 3, the sqlite3 module requires a ? as a placeholder, not %s or some other format string.
According to the Python 2 documentation, a %s placeholder could be used like this:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
# Never do this -- insecure!
symbol = 'IBM'
c.execute("select * from stocks where symbol = '%s'" % symbol)
but that's a simple format string, not actually the database's placeholder. Also, as the comment shows, you should never build queries that way because it makes them vulnerable to SQL injection. Rather, you should build them like this, using a ? instead:
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
# Do this instead
t = (symbol,)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
The documentation has more details, but I believe that is the solution to the error you posted.

Categories

Resources