Thanks for taking the time to read this. This will be a long post to explain the problem. I could not find the answer in all the usual sources.
Problem: I had a problem using the select statement with python to call data from a table in a mysql database.
System and versions:
Linux ubuntu 2.6.38-14-generic
Here is the table:
mysql> describe hashes; +-------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | id | varchar(20) | NO | PRI | NULL | | | hash | varbinary(4) | NO | MUL | NULL | | +-------+--------------+------+-----+---------+-------+
Here are the answers I want to get with a regular mysql query:
mysql> SELECT id FROM hashes WHERE hash='f'; +------+ | id | +------+ | 0x67 | +------+ mysql> SELECT id FROM hashes WHERE hash='ff'; +--------+ | id | +--------+ | 0x6700 | +--------+
As before, these are the expected answers and how I created the database.
My code is:
import mysql.connector from database import login_info import sys db = mysql.connector.Connect(**login_info) cursor = db.cursor() data = 'ff' cursor.execute("""SELECT * FROM hashes WHERE hash=%s""", (data)) rows = cursor.fetchall() print rows for row in rows: print row[0]
This returns the expected result:
[(u'0x67', 'f')] 0x67
If I change the data to: data = 'ff' I get the following error:
Traceback (most recent call last): File "test.py", line 11, in <module> (data)) File "/usr/local/lib/python2.7/dist-packages/mysql_connector_python-0.3.2_devel- py2.7.egg/mysql/connector/cursor.py", line 310, in execute "Wrong number of arguments during string formatting") mysql.connector.errors.ProgrammingError: Wrong number of arguments during string formatting
OK So, I am adding a string formatting character to my SQL statement like this:
cursor.execute("""SELECT * FROM hashes WHERE hash=%s%s""", (data))
And I get the following response:
[(u'0x665aa6', "f'f")] 0x665aa6
and it should be at 0x6700.
I know that I have to transfer data with a single% s character. This is how I built my database table using one% s per variable:
cursor.execute(""" INSERT INTO hashes (id, hash) VALUES (%s, %s)""", (k, hash))
Any ideas how to fix this?
Thanks.