I'm currently working on a basic query which insert data depending on the input parameters, and I'm unable to perfom it.
cur.execute("INSERT INTO foo (bar1, bar2) values (?, ?)", (foo1, foo2))
I have this error message:
Exception in Tkinter callback Traceback (most recent call last):
File "/usr/lib/python3.2/tkinter/init.py", line 1426, in call
return self.func(*args) File "test.py", line 9, in register
cur.execute("INSERT INTO foo (bar1, bar2) values (?,?)", (foo1, foo2)) File
"/usr/local/lib/python3.2/dist-packages/pymysql/cursors.py", line 108,
in execute
query = query % escaped_args TypeError: unsupported operand type(s) for %: 'bytes' and 'tuple'
foo1 and foo2 are both string type. I tried with %s, same error.
It seems like a bug in cursors.py. As suggested here and here you should replace this line in cursors.py:
query = query % conn.escape(args)
With this:
query = query.decode(charset) % conn.escape(args)
In case it didn't work try this one instead:
query = query.decode(charset) % escaped_args
Related
I am trying to add multiple records into a database using mysql-connector-python. I was able to add one record initially but for multiple records, this error has been persistent.
class DataBase:
def __init__(self):
try:
self.connection = mysql.connector.connect(host='xx.xxx.xx.xx',
database='XXX',
user='XXXX',
password='xxxx')
except Error as error:
print("Failed to connect: {}".format(error))
def store_into_table(self, df):
mySql_insert_query = """INSERT INTO data ('data_id', 'a', 'b', 'c') VALUES ('%S','%S', '%S', '%S') """
records_to_insert = df
cursor = self.connection.cursor()
cursor.executemany(mySql_insert_query, records_to_insert)
self.connection.commit()
print(cursor.rowcount, " Records inserted successfully into data table")
The variable that I am passing to an instance of DataBase is:
data = [('101', 'name_1', '3', 'sample'), ('102', 'name_2', '5', 'sample_1')]
Exception being thrown:
Traceback (most recent call last):
File "/Users/dev/anaconda3/envs/sql/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 317, in _batch_insert
"Not all parameters were used in the SQL statement")
ProgrammingError: Not all parameters were used in the SQL statement
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<ipython-input-123-44fdf194cd10>", line 1, in <module>
db.store_into_table(data)
File "/Users/dev/Detector/database.py", line 30, in store_into_table
cursor.executemany(mySql_insert_query, records_to_insert)
File "/Users/dev/anaconda3/envs/sql/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 350, in executemany
stmt = self._batch_insert(operation, seq_params)
File "/Users/dev/anaconda3/envs/sql/lib/python3.7/site-packages/mysql/connector/cursor_cext.py", line 329, in _batch_insert
"Failed executing the operation; %s" % err)
InterfaceError: Failed executing the operation; Not all parameters were used in the SQL statement
Any clues as to why this isn't working?
Try this:
mySql_insert_query = """INSERT INTO data (data_id, a, b, c) VALUES (%s, %s, %s, %s) """
Im having a problem inserting a variable into sqlite3 and the variable is hashed.
Here's my code:
if passadefinir == passadefinir2:
maindb.execute("DELETE FROM Password WHERE ID = 'not'")
maindb.execute("INSERT INTO Password(ID) VALUES ('set')")
encriptacao = hashlib.sha1(passadefinir2.encode())
encriptado = (encriptacao.hexdigest(),)
maindb.execute("INSERT INTO Password(Password) VALUES (?)" (encriptado,))
conn.commit()
Here's the error:
Traceback (most recent call last):
File "sqlitetesting.py", line 28, in
maindb.execute("INSERT INTO Password(Password) VALUES (?)" (encriptado,))
TypeError: 'str' object is not callable
Have a nice day :D,
Luis Duarte.
You can substitute using String's format method
password_var = 'your password'
insert_statement = 'INSERT INTO Password(Password) VALUES ({0})'.format('\'' + password_var + '\'')
then run the execute method as:
maindb.execute(insert_statement)
Why am I getting TypeError: not all arguments converted during string formatting when trying to execute this query? I need to be able to append %{}% to the IP I am passing in so that i can run a LIKE mysql query.
If this isn't the correct way to parameterize a LIKE query using the % wildcard, how do you do this?
Class:
class IpCleaner(object):
def __init__(self, ip):
self.ip = ip
self.iplike = '%{}%'.format(self.ip)
def lookup(self):
self.dbconnect()
select_query = (
"SELECT `name`,`source`,`destination` FROM mytable "
"WHERE (`source` LIKE ? OR `destination` ? );"
)
params = [self.iplike, self.iplike]
print params
self.cur.execute(select_query, params)
print self.cur.fetchall()
Instantiation:
a = IpCleaner('74.121.242.2')
a.lookup()
output:
Traceback (most recent call last):
['%74.121.242.2%', '%74.121.242.2%']
File "/home/dobbs/shunlibs/IpCleaner.py", line 87, in <module>
a.palorulelookup()
File "/home/dobbs/shunlibs/IpCleaner.py", line 81, in lookup
self.cur.execute(select_query, params)
File "/usr/lib64/python2.7/site-packages/pymysql/cursors.py", line 164, in execute
query = self.mogrify(query, args)
File "/usr/lib64/python2.7/site-packages/pymysql/cursors.py", line 143, in mogrify
query = query % self._escape_args(args, conn)
TypeError: not all arguments converted during string formatting
use %s instead of ? in the select_query variable
I am trying to do an insert with PyMySQL in Python3, but I keep getting the following:
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
My code is as follows:
query = ("INSERT INTO table_name ",
"(type,sub) ",
"VALUES ",
"(%s,%s)")
#Execute the query
print("Category: %s" % category)
print("Category is string:",isinstance(category,str))
print("Category_group: %s" % category_group)
print("Category_group is string:",isinstance(category,str))
self.DB['master']['cursor'].execute(query,(category,category_group,))
self.DB['master']['con'].commit()
Which when running outputs:
Category: Amusement Park
Category is string: True
Category_group: Parks
Category_group is string: True
Traceback (most recent call last):
File "main.py", line 87, in <module>
m()
File "main.py", line 82, in __call__
self.deal.processdeal(deal=item,store=store)
File "file.py", line 85, in processdeal
btype = self.obtainBusinessType(deal['category'],deal['categoryGroup'])
File "file.py", line 59, in obtainBusinessType
self.DB['master']['cursor'].execute(query,(category,category_group,))
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pymysql/cursors.py", line 130, in execute
query = query % self._escape_args(args, conn)
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
The output statements indicate that I am feeding strings as parameters, so why is it complaining about tuples?
Your problem is how you are building your query variable.
query = ("INSERT INTO table_name ",
"(type,sub) ",
"VALUES ",
"(%s,%s)")
print query
>>>('INSERT INTO table_name ', '(type,sub) ', 'VALUES ', '(%s,%s)')
query = query % ('hello', 'world')
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
Notice how your query is being outputted as a tuple, which causing the error.
You can use a str:
query = "INSERT INTO table_name (type,sub) VALUES (%s,%s)"
Or you remove the , from your query
query = ("INSERT INTO table_name "
"(type,sub) "
"VALUES "
"(%s,%s)")
Alternatively, as Kindall stated, you can also use triple-quote for multi-line strings
"""INSERT INTO table_name
(type,sub)
VALUES
(%s,%s)"""
This is my code:
now = datetime.datetime.now().replace(microsecond=0)
curs.execute("SELECT name, msgDate, FROM test where msgDate=%s",(now))
I got these msgs:
File "C:\Python\lib\site-packages\mysql\connector\cursor.py", line 220, in _process_params
res = list(map(to_mysql,res))
TypeError: 'datetime.datetime' object is not iterable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\projectse\Email\src\a.py", line 65, in <module>
curs.execute("SELECT name, msgDate FROM messages where msgDate=%s",(now))
File "C:\Python\lib\site-packages\mysql\connector\cursor.py", line 300, in execute
stmt = operation % self._process_params(params)
File "C:\Python\lib\site-packages\mysql\connector\cursor.py", line 225, in _process_params
"Failed processing format-parameters; %s" % e)
mysql.connector.errors.ProgrammingError: -1: Failed processing format-parameters;
'datetime.datetime' object is not iterable
Any tips?
I think you should replace:
curs.execute("SELECT name, msgDate, FROM test where msgDate=%s",(now))
with:
curs.execute("SELECT name, msgDate, FROM test where msgDate=%s",%(now))
and use this for your time variable:
import time
now=time.strftime('%Y-%m-%d %H:%M:%S')
Try seeing what now = str(datetime.datetime.now().replace(microsecond=0)) looks like in the python interpreter, if you're curious why that's a problem.
now = datetime.datetime(2012, 2, 23, 0, 0)
now.strftime('%m/%d/%Y')
curs.execute("SELECT name, msgDate, FROM test where msgDate=:now",dict(now=str(now))
please try converting date to string format and execute