在Python中从MySQLdb中提取条目

时间:2014-03-05 02:27:03

标签: 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,usernamefield,passwordfield,field3)。如何添加到此代码以便我可以指定拉入条目WHERE user =“therightuser”AND pass =“therightpass”然后从tha条目中拉取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")

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

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

如果您希望能够按列名访问数据,即 print 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