简体   繁体   English

如何将mySQL查询存储为python字典并稍后在脚本中调用?

[英]How to store mySQL query as python dictionary and call later in script?

I have a table called " uid " which has two fields, rfid and empid : 我有一个名为“ uid ”的表,它有两个字段, rfidempid

  • EXAMPLE RECORD 1 rfid = 88 999 33 555 empid = 1 示例记录1 rfid = 88 999 33 555 empid = 1
  • EXAMPLE RECORD 2 rfid = 64 344 77 222 empid = 2 示例记录2 rfid = 64 344 77 222 empid = 2

I would like to run a query which stores all of these values in a python dictionary, and allows me to set the rfid number as a variable (MyRFID) to be called later in the script: 我想运行一个查询,它将所有这些值存储在python字典中,并允许我将rfid编号设置为稍后在脚本中调用的变量(MyRFID):

db = MySQLdb.connect("MyIp", "MyUser", "MyPass", "MyDB", cursorclass=MySQLdb.cursors.DictCursor)
curs=db.cursor()
curs.execute("""SELECT number, empid FROM rfid """)

So that later in the code I can check to see if I get a match from an existing variable: 因此,稍后在代码中我可以检查是否从现有变量中获得匹配:

if MyVariable == MyRFID:
    #Create new record for that empid

I think you're looking for the fetchall method. 我想你正在寻找胎儿方法。 After you call 打电话后

cur.execute("""SELECT number, empid FROM rfid """)

you would do: 你会这样做:

rows = cur.fetchall()

and then rows would contain a list of tuples. 然后行将包含元组列表。 If you specifically need it to be a dictionary, you could just do dict(rows) in this example but that only works because your query happens to return two columns. 如果您特别需要它作为字典,您可以在此示例中执行dict(rows) ,但这只能起作用,因为您的查询恰好返回两列。 If it was more than two columns you would need something like: 如果它超过两列,您需要以下内容:

rows_dict = dict([ k[0], k[1:]) for k in rows])

(see: Converting List of 3 Element Tuple to Dictionary ) (请参阅: 将3元素元组的列表转换为字典

If the dictionary you were imagining had column names as keys you need to look at DictCursor ( Python: use mysqldb to import a MySQL table as a dictionary? ). 如果你想象的字典有列名作为键,你需要查看DictCursor( Python:使用mysqldb将MySQL表作为字典导入? )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM