MySQL和Python Select语句问题
感谢您抽出时间阅读此文章。解释这个问题需要很长时间。我还没能从所有常见的资料中找到答案 问题: 在使用python中的select语句从mysql数据库中的表中调用数据时,我遇到了一个问题 系统和版本:MySQL和Python Select语句问题,python,mysql,select,encoding,Python,Mysql,Select,Encoding,感谢您抽出时间阅读此文章。解释这个问题需要很长时间。我还没能从所有常见的资料中找到答案 问题: 在使用python中的select语句从mysql数据库中的表中调用数据时,我遇到了一个问题 系统和版本: 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.
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)
这是桌子:
mysql> describe hashes;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | varchar(20) | NO | PRI | NULL | |
| hash | varbinary(4) | NO | MUL | NULL | |
+-------+--------------+------+-----+---------+-------+
以下是我希望通过普通mysql查询得到的响应:
mysql> SELECT id FROM hashes WHERE hash='f';
+------+
| id |
+------+
| 0x67 |
+------+
mysql> SELECT id FROM hashes WHERE hash='ff';
+--------+
| id |
+--------+
| 0x6700 |
+--------+
与之前一样,这些是预期的响应,以及我是如何设计DB的
我的代码:
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]
这将返回我期望的结果:
[(u'0x67', 'f')]
0x67
如果我将数据更改为:
数据='ff'
我收到以下错误:
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
我得到以下回应:
[(u'0x665aa6', "f'f")]
0x665aa6
它应该是0x6700
我知道我应该用一个%s字符传递数据。这就是我构建数据库表的方式,每个变量使用一个%s:
cursor.execute("""
INSERT INTO hashes (id, hash)
VALUES (%s, %s)""", (k, hash))
有没有办法解决这个问题
谢谢。您的execute语句似乎不太正确。我的理解是,它应该遵循模式
cursor.execute(,)
,在元组位置只放一个值,实际上它只是一个字符串。要使第二个参数成为正确的数据类型,需要在其中加一个逗号,因此语句如下所示:
cursor.execute("""SELECT
* FROM hashes
WHERE hash=%s""",
(data, ))
cursor.execute("""SELECT
* FROM hashes
WHERE hash=%s""",
(data, ))