从MySQL数据库中以字典格式获取数据

3 投票
1 回答
5580 浏览
提问于 2025-04-18 17:38
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 个回答

1

你只缺少一行代码。你可以像这样把 variable 转换成字典:

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

撰写回答