从python中以字典格式从MySQL数据库中检索数据

时间:2014-08-18 10:09:18

标签: python mysql

import MySQLdb
def Network():

    dict = {'CISCO' : 'NEXUS', 'JUNIPER' : 'JUNO', 'Alcatel' : 'Alc' }


    #len(dict)
    return (dict)



def db_store(variable):
    con = MySQLdb.connect("localhost","root","root","fs_company" )
    cur = con.cursor()
    for key,value in variable.items():
        cur.execute('''INSERT into google (name, company) values (%s, %s)''', (key, value))
        con.commit()
    cur.execute("""SELECT * FROM google""")
    variable = cur.fetchall()
    #print variable



variable = Network()
db_store(variable)

我有上面的代码将数据存储到mysql数据库,我想以字典格式从数据库中检索数据。需要同样的帮助

1 个答案:

答案 0 :(得分:0)

您只缺少一行。您可以将变量转换为dict,如下所示:

cur.execute("""SELECT * FROM google""")
out = cur.fetchall()
variable = {key:val for key,val in out}
print(variable)