2012-05-01 139 views
6

感谢您花时间阅读本文。这将是一个很长的帖子来解释这个问题。我无法在所有常见来源中找到答案。MySQL和Python Select语句问题

问题: 我有一个与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.62-0ubuntu0.11.04.1 (Ubuntu) 

这里的桌子:我通过正常的MySQL查询想要

mysql> describe hashes; 
+-------+--------------+------+-----+---------+-------+ 
| Field | Type   | Null | Key | Default | Extra | 
+-------+--------------+------+-----+---------+-------+ 
| id | varchar(20) | NO | PRI | NULL |  | 
| hash | varbinary(4) | NO | MUL | NULL |  | 
+-------+--------------+------+-----+---------+-------+ 

以下是回应:和以前一样

mysql> SELECT id FROM hashes WHERE hash='f'; 
+------+ 
| id | 
+------+ 
| 0x67 | 
+------+ 

mysql> SELECT id FROM hashes WHERE hash='ff'; 
+--------+ 
| id  | 
+--------+ 
| 0x6700 | 
+--------+ 

,这些都是预期的回应以及我如何设计数据库。

我的代码:

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 

好的。所以,我一个字符串格式化字符添加到我的SQL语句,像这样:

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

我也得到如下回应:

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

,应该由0x6700。

我知道我应该传递一个%s字符的数据。这就是我如何建立我的数据库表,每个变量使用一个%s:

cursor.execute(""" 
INSERT INTO hashes (id, hash) 
VALUES (%s, %s)""", (k, hash)) 

任何想法如何解决这个问题?

谢谢。

回答

23

您的执行语句看起来不太正确。我的理解是它应该遵循cursor.execute(<select statement string>, <tuple>)这样的模式,并且在元组位置只放入一个值,它实际上只是一个字符串。要使第二个参数为正确的数据类型,您需要在其中输入逗号,因此您的语句如下所示:

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

太棒了!这解决了我的问题。谢谢! – JoshP