MySQL 和 Python Select 语句问题

2023-12-26

感谢您抽时间阅读。这将是一个很长的帖子来解释这个问题。我无法在所有常用来源中找到答案。

问题: 我在使用 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> 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 |
+--------+

和以前一样,这些是预期的响应以及我如何设计数据库。

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 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))

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

Thanks.


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

cursor.execute("""SELECT
            * FROM hashes
            WHERE hash=%s""",
            (data, ))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MySQL 和 Python Select 语句问题 的相关文章

随机推荐