python - 使用 Python 从 MySQLdb 中提取条目

标签 python mysql select raspberry-pi

我正在尝试使用 Python 连接到 MySQL 数据库,查询一个字段的值,如果它与预定义值匹配则返回。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb

con = mdb.connect('localhost', 'user', 'pass', 'db');
with con: 
    cur = con.cursor()
    cur.execute("SELECT * FROM tablename")
    rows = cur.fetchone()
    for row in rows:
        print row

这是我到目前为止所拥有的,它返回一个类似于(0L,用户名字段,密码字段,字段3)的值。我如何添加到此代码,以便我可以指定提取条目 WHERE user = "therightuser"AND pass = "therightpass",然后从该条目提取 field3 的值。类似于...

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb as mdb

con = mdb.connect('localhost', 'user', 'pass', 'db');
with con: 
    cur = con.cursor()
    cur.execute("SELECT * FROM table name WHERE user ='therightuser' AND pass ='therightpass'")
    rows = cur.fetchone()
    for row in rows:
        print row[field3]
    if field3 == "yes":
            print ("The field says yes")
    else:
            print ("The field says no")

最佳答案

尝试以下操作:

cur.execute("SELECT * FROM table name WHERE user ='therightuser' AND pass ='therightpass'")
    row = cur.fetchone()
    print row[3]
    if field3 == "yes":
            print ("The field says yes")
    else:
            print ("The field says no")

或者,更安全的实现是:

cur.execute("""SELECT * FROM table name WHERE user=%s AND pass=%s""", ('therightuser', 'therightpass'))

如果您希望能够通过列名称访问数据,即 打印row['field3'],可以使用以下方法:

def FetchOneAssoc(cursor) :
    data = cursor.fetchone()
    if data == None :
        return None
    desc = cursor.description

    dict = {}

    for (name, value) in zip(desc, data) :
        dict[name[0]] = value

    return dict

因此,在 cur.execute(...) 之后,您将拥有:

row = FetchOneAssoc(cur)
print row['field3']

引用http://www.ianhowson.com/a-quick-guide-to-using-mysql-in-python.html

关于python - 使用 Python 从 MySQLdb 中提取条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187286/

相关文章:

php - 弱类型语言的优点(和缺点)是什么?

Python docker-py 连接被拒绝

java - MySql 是否支持 Java SE 应用程序的连接池?

MySQL 使用 if 语句从多个表中进行 SELECT

mysql - 从 Oracle Apex 中的 3 个表中选择数据

mysql返回更新结果

python - Skip Connections的科学解释

python - 使用 python 构建 Web 应用程序

c# - c# asp.net 程序执行过程中遇到 fatal error

php - 在一定时间内显示DIV