MySQL and Python Release Issues

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 #58-Ubuntu SMP Tue Mar 27 20:04:55 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux Python: 2.7.1+ MySql: Server version: 5.1.62-0ubuntu0.11.04.1 (Ubuntu) 

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.

+6
source share
1 answer

Your run statement does not look completely correct. I understand that it must follow the cursor.execute( <select statement string>, <tuple>) pattern and, placing only one value in the tuple, it is actually just a string. To make the second argument the correct data type, you need to enter a comma there, so your statement will look like this:

 cursor.execute("""SELECT * FROM hashes WHERE hash=%s""", (data, )) 
+23
source

Source: https://habr.com/ru/post/914656/


All Articles