Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中从MySQLdb中提取条目_Python_Mysql_Select_Raspberry Pi - Fatal编程技术网

在Python中从MySQLdb中提取条目

在Python中从MySQLdb中提取条目,python,mysql,select,raspberry-pi,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

我试图使用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。如何添加到该代码中,以便指定从user=therightuser和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'))
如果您希望能够通过列名访问数据,即 打印行['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']

参考

它在哪里,而不是WHEN@m1Lb4nKs谢谢你知道如何解析这个查询吗?你所拥有的应该可以工作,尽管它没有多大意义。如果您要获取一个,那么就不需要循环。fetchall和loop或者fetchone和直接访问值。我从未使用过mysqldb,但您可能需要使用第[3]行来代替它?它很有效。谢谢你给我选择:干杯。