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.
Related
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.
I'm learning programming with python and trying to implement the safest possible MySQL queries starting with the simple SELECT ones. The problem is whenever I use coma in a query I got the following error:
cursor.execute(query)
File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 536, in execute
stmt = operation.encode(self._connection.python_charset)
AttributeError: 'tuple' object has no attribute 'encode'
I am aware of the fact that coma itself isn't a source of a problem but I tried many different MySQL syntax and everytime I use a come I got this "AttributeError: 'tuple' object has no attribute 'encode'" error.
I also tried to change MySQL database encoding - nothing changes. The code is below.
import mysql.connector
conn = mysql.connector.connect(
charset='utf8',
# init_command='SET NAMES UTF8',
host="10.0.0.234",
user="x",
passwd="x>",
database="x",
)
print(conn.is_connected())
param = "test"
cursor = conn.cursor()
# =========== query below does work ========
# query = ("SELECT * from list WHERE username LIKE '%test%'")
# ============ query below does work =======
# query = ("SELECT * from list HAVING username = '%s'" % param)
# ============ query below doesn't work =====
# query = ("SELECT * from list HAVING username = %s", (param,))
# ============= query below doesn't work =====
query = "SELECT * from list WHERE username = :name", {'name': param}
cursor.execute(query)
result = cursor.fetchall()
for x in result:
print(x)
conn.close()
Any ideas what am I doing wrong?
The answer is a little bit tricky, but it is in essence because of what the actual value of the 'query' variable is...
For example:
# 1.
query = ("SELECT * from list WHERE username LIKE '%test%'")
# when you do this, query is a string variable,
# NB: the parentheses are not necessary here
# so when you call
cursor.execute(query)
# the value passed into the execute call is the string "SELECT * from list WHERE username LIKE '%test%'"
# 2.
query = ("SELECT * from list HAVING username = '%s'" % param)
# when you do this, query is the result of a string formatting operation
# This is a Python 2 form of string formatting
# The discussion here probably makes it more clear:
# https://stackoverflow.com/questions/13945749/string-formatting-in-python-3
# it is almost the same as doing this:
query = "SELECT * from list HAVING username = 'test'"
# so when you call
cursor.execute(query)
# the value passed into the execute call is the string "SELECT * from list HAVING username = 'test'"
# 3.
query = ("SELECT * from list HAVING username = %s", (param,))
# This operation is assigning a 2-value tuple into the query variable
# The first value in the tuple is the string "SELECT * from list HAVING username = %s"
# The second value in the tuple is a 1-value, with 'test' as its first value
# 4.
query = "SELECT * from list WHERE username = :name", {'name': param}
# This is similar to #3, but the values in the tuple are instead
# query[0] == "SELECT * from list WHERE username = :name"
# query[1] is a dictionary: {'name': param}
Both 3 and 4 above are not calling the MySQL execute with the parameters you are expecting (see API here). You probably need to do one of:
unpack the query tuple into separate variables, and call the function with them
operation, params = query # unpack the first elem into operation, and second into params
cursor.execute(operation, params)
just index into the query tuple
cursor.execute(query[0], query[1])
# NB: you could also use the 'named parameters' feature in Python
cursor.execute(query[0], params=query[1])
Use the 'unpacking arguments list' (SPLAT operator)
cursor.execute(*query)
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)
I have a problem passing a string to a query in python for postgresql. In particular I have the following script that works perfectly:
y = 'test'
for i in un:
crs = conn.cursor()
query = """
select *
FROM test
WHERE test.vin_id = %s
;"""
s_id = i
crs.execute(query,[s_id])
s_out = crs.fetchall()
but if I change test with the variable y it gives me an error.
for i in un:
crs = conn.cursor()
query = """
select *
FROM %s
WHERE %s.vin_id = %s
;"""
s_id = i
crs.execute(query,[y,y,s_id])
s_out = crs.fetchall()
ProgrammingError: syntax error at or near "'test'"
LINE 3: FROM 'test'
Unfortunately it does not work and I have the same problem when I try to put sentences in the middle, for instance:
query1 = """
SELECT *
FROM test1
WHERE %s LIKE '%' || vin_id || '%'
;"""
crs1 = conn.cursor()
crs1.execute(query1, [s_id])
You can use AsIs:
from psycopg2.extensions import AsIs
for i in un:
crs = conn.cursor()
query = """
select *
FROM %s
WHERE %s.vin_id = %s
;"""
s_id = i
crs.execute(query,[AsIs(y),AsIs(y),s_id])
s_out = crs.fetchall()
I can't show the data from database sqlite in python.
connection = sqlite3.connect('db')
connection.cursor().execute('CREATE TABLE IF NOT EXISTS users ( \
id TEXT, \
name TEXT, \
avatar TEXT \
)')
# In cycle:
query = 'INSERT INTO users VALUES ("' + str(friend.id) + '", "' + friend.name + '", "' + friend.avatar +'" )'
print query
connection.cursor().execute(query)
connection.commit()
# After cycle
print connection.cursor().fetchall()
Sample output of query variable:
INSERT INTO users VALUES ("111", "Some Name", "http://avatar/path" )
In result, fetchall returns empty tuple. Why?
UPD
Forgotten code:
connection.cursor().execute('SELECT * FROM users')
connection.cursor().fetchall()
→
[]
INSERT does not return data. To get the data back out, you'll have to issue a SELECT statement.
import sqlite3
con = sqlite3.connect("db")
con.execute("create table users(id, name, avatar)")
con.execute("insert into users(id, name, avatar) values (?, ?, ?)", (friend.id, friend.name, friend.avatar))
con.commit()
for row in con.execute("select * from users")
print row
con.close()
Because the create table string as displayed is syntactically invalid Python, as is the insert into string.
Actually, the answer to your first question is: because you use different cursors.
connection.cursor() creates a new cursor in the connection you created before. fetchall() gives you the results of the query you executed before in that same cursor. I.e. what you did was this:
# After cycle
cursor1 = connection.cursor()
cursor1.execute('SELECT * FROM users')
cursor2 = connection.cursor()
cursor2.execute("")
cursor2.fetchall()
What you should have done was this:
# After cycle
cursor = connection.cursor()
cursor.execute('SELECT * FROM users')
print cursor.fetchall()