2012-05-01 30 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