【问题标题】:Python: use mysqldb to import a MySQL table as a dictionary?Python:使用 mysqldb 将 MySQL 表作为字典导入?
【发布时间】:2011-01-11 22:06:00
【问题描述】:

任何人都知道我如何使用 mysqldb 将包含大量行的 MySQL 表转换为 Python 中的字典对象列表?

我的意思是将一组 MySQL 行(包含列“a”、“b”和“c”)转换为如下所示的 Python 对象:

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ]

谢谢:)

【问题讨论】:

  • 如果可以的话,我会在此处添加标签dictionary 和/或cursor

标签: python mysql dictionary


【解决方案1】:

MySQLdb 为此有一个单独的游标类,即 DictCursor。您可以将要使用的游标类传递给 MySQLdb.connect():

import MySQLdb.cursors
MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)

【讨论】:

  • 完美,谢谢!对于其他阅读者,您还需要将“import MySQLdb.cursors”添加到 Python 脚本的顶部以包含它。
  • 你一定错过了我实际上在代码 sn-p 中包含 MySQL.cursors 导入的事实。
  • 对于其他阅读者,您还需要在import MySQLdb.cursors 之后的某处添加MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor) 以使sn-p 工作。 (对不起,我无法抗拒!:D)
【解决方案2】:

如果您需要使用更多游标,并且只需要一个是 MySQLdb.cursors.DictCursor,您可以这样做:

import MySQLdb
db = MySQLdb.connect(host='...', db='...', user='...t', passwd='...')

list_cursor = db.cursor()
dict_cursor = db.cursor(MySQLdb.cursors.DictCursor)

【讨论】:

  • 需要添加import MySQLdb.cursors 否则会在python 3.4中引发错误
  • @DavidLavieri 在带有mysqlclient 1.3.12 的Python 3.6 中不需要额外的import 语句
【解决方案3】:

我认为mysql.connector 比 MySQLdb 更容易将 select 转换为 dict,并且支持更多 Python 版本:

cursor = conn.cursor(dictionary=True)

详细示例:

import mysql.connector # pip install mysql-connector-python

mydb = mysql.connector.connect(host="localhost", user="user", passwd="pass", database="dbname")
cursor = conn.cursor(dictionary=True)
sql = "SELECT * FROM `table` WHERE 1"
mycursor.execute(sql)
rows = mycursor.fetchall()
for row in rows:
    row["col"]

【讨论】:

  • 这应该是公认的答案 - 更容易,不需要额外的导入。
【解决方案4】:

这是一篇古老的帖子,虽然这个答案并不完全是 OP 所要寻找的,但它的思路大致相同。它不是生成字典列表,而是生成列表字典:

还想我会提供生成字典的完整代码:

import MySQLdb
import MySQLdb.cursors

dict_serv = MySQLdb.connect(host = 'localhost', user = 'root', passwd = 'mypassword', cursorclass = MySQLdb.cursors.DictCursor)

with dict_serv as c:
    c.execute("USE mydb")
    c.execute("SELECT col1, col2 FROM mytable WHERE id = 'X123'")

    # Save the dictionary to a separate variable
    init_dict = c.fetchall()

    # This line builds the column headers
    sql_cols = [ col[0] for col in c.description ]

    # This is a list comprehension within a dictionary comprehension
    # which builds the full dictionary in a single line.  
    sql_dict = { k : [ d[k] for d in init_dict ] for k in sql_cols }

产量:

{ 'col1': ['apple','banana'], 'col2':['red','yellow'] }

【讨论】:

    【解决方案5】:

    使用 Python >= 3.6;在这里它可以这样做:

    OBS.:这里我使用 2 个数据库类型 ORACLE 12g 和 MYSQL 5.6 ;并且主服务器是ORACLE,mysql只有部分软件使用……然后……我的连接类的代码:

    这里是来自 shellscript 代码...然后我只是带一个字符串在这里显示...

    myp3 = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX PASSWD MYSQL XXXXXXXXXXXXXXXXXXXXXXXXXXX'

    import cx_Oracle
    import MySQLdb
    import MySQLdb.cursors
    
    class oracle(object):
        def __init__(self, serverORACLE=3, MYSQL='N', serverMYSQL=3):
            ## ORACLE connection!
            try:
    
            if serverORACLE == 1:
                self.db = cx_Oracle.connect('sys/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
                print('ORACLE [ system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')
    
            if serverORACLE == 2:
                self.db = cx_Oracle.connect('system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
                print('ORACLE [ system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')
    
            if serverORACLE == 3:
                self.db = cx_Oracle.connect('userLEVEL1/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
                print('ORACLE [ userLEVEL1/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')
    
            if serverORACLE == 4:
                self.db = cx_Oracle.connect('userLEVEL2/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
                print('ORACLE [ userLEVEL2/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')
                
            self.cursor = self.db.cursor()
            
        except Exception as e:
            count = 0
            S1 = ''
            for W in str(e):
                S1+=W
                count+=1 
                if count >= 40:
                    S1+=' \n'
                    count = 0
            print('\n\n ORACLE DATABASE ===> CONECTION FAILED!', 
                        '\n error - module: ', S1)
    
        ##conexao MYSQL
        if MYSQL=='S': 
            try:
                if serverMYSQL == 1:
                    self.dbMySQL = MySQLdb.connect(user='root', host='XXXXXX HOST XXXXX', use_unicode=True, cursorclass=MySQLdb.cursors.DictCursor,
                                                    charset='utf8', port=3306, passwd=myp3, db='XXXX')
                    print('MySQL [ root / XXXXXX HOST XXXXX:3306 ] ===> CONNECTED')
    
                if serverMYSQL == 2:
                    self.dbMySQL = MySQLdb.connect(user='XXXX USER XXXXX', host='XXXXXX HOST XXXXX', use_unicode=True, cursorclass=MySQLdb.cursors.DictCursor,
                                                    charset='utf8', port=3306, passwd=myp3, db='XXXX')
                    print('MySQL [ XXXX USER XXXXX / XXXXXX HOST XXXXX:3306 ] ===> CONNECTED')
    
                self.cursorMYSQL = self.dbMySQL.cursor()
            
            except Exception as e:
                count = 0
                S1 = ''
                for W in str(e):
                    S1+=W
                    count+=1 
                    if count >= 40:
                        S1+=' \n'
                        count = 0
                print('\n\n MYSQL DATABASE ===> CONECTION FAILED!', 
                        '\n error - module: ', S1)
    

    """

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-21
      • 2013-05-22
      • 2018-05-11
      • 1970-01-01
      • 2014-11-22
      • 2016-01-25
      • 2014-11-09
      • 2017-10-22
      相关资源
      最近更新 更多