我正在尝试使用 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/