MySQL and Python Select Statement Issues

2024/9/25 22:29:49

Thanks for taking the time to read this. It's going to be a long post to explain the problem. I haven't been able to find an answer in all the usual sources.

Problem: I am having an issue with using the select statement with python to recall 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's 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 responses that I want via a normal 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 responses that are expected and how I designed the DB.

My code:

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 hashesWHERE hash=%s""",(data))rows = cursor.fetchall()
print rows
for row in rows:print row[0]

This returns the result I expect:

[(u'0x67', 'f')]
0x67

If I change data to :data = 'ff' I receive 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 add a string formatting character to my SQL statement as so:

cursor.execute("""SELECT* FROM hashesWHERE hash=%s%s""",(data))

And I get the following response:

[(u'0x665aa6', "f'f")]
0x665aa6

and it should by 0x6700.

I know that I should be passing the data with one %s character. That 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.

Answer

Your execute statement doesn't seem quite correct. My understanding is that it should follow the pattern cursor.execute( <select statement string>, <tuple>) and by putting only a single value in the tuple location it is actually just a string. To make the second argument the correct data type you need to put a comma in there, so your statement would look like:

cursor.execute("""SELECT* FROM hashesWHERE hash=%s""",(data, ))
https://en.xdnf.cn/q/71530.html

Related Q&A

How to pass variable in url to Django List View

I have a Django generic List View that I want to filter based on the value entered into the URL. For example, when someone enters mysite.com/defaults/41 I want the view to filter all of the values mat…

Django Select Option selected issue

I tried to follow some examples on stackoverflow for option selected in select list but still, I could not get it work.This is my code snippet<select name="topic_id" style="width:90%&…

reading tab-delimited data without header in pandas

Im having trouble using pandas to open tab-delimited data without headers.My test data (actually contains 200 lines, of which I am showing the first 10):Tag19184 CTAAC hffef 1 a 36 - chr1…

Python Try/Except with multiple except blocks

try:raise KeyError() except KeyError:print "Caught KeyError"raise Exception() except Exception:print "Caught Exception"As expected, raising Exception() on the 5th line isnt caught i…

How to install trax, jax, jaxlib on M1 Mac on macOS 12?

trax New to trax, Im trying to run it locally (macOS 12.1, Apple Silicon ARM M1 processor, 8GB RAM, Anaconda), but Im running into some issues. In an environment with python 3.8.5, I installed trax run…

How do I match a word in a text file using python?

I want to search and match a particular word in a text file.with open(wordlist.txt, r) as searchfile:for line in searchfile:if word in line:print lineThis code returns even the words that contain subst…

Unable to Delete Videos with the Youtube Data API

Cant get deleting videos to work using the Youtube Data API. Im using the Python Client Library.All of this seems straight from the docs, so Im really confused as to why its not working. Heres my fun…

LLDB Python scripting in Xcode

Ive just discovered this handy feature of LLDB that allows me to write Python scripts that have access to variables in the frame when Im on a breakpoint in LLDB. However Im having a few issues when usi…

What technologies exist to create stand alone executables for Python 3?

Other than cx_Freeze, are there any other current maintained tool suites to generate stand alone executables for Python 3k?Are there any other techniques for minimizing preinstallation requirements un…

running multiple threads in python, simultaneously - is it possible?

Im writing a little crawler that should fetch a URL multiple times, I want all of the threads to run at the same time (simultaneously).Ive written a little piece of code that should do that.import thre…