Python:使用mysqldb将MySQL表导入为字典?

时间:2010-02-01 21:31:19

标签: python mysql dictionary

任何人都知道如何使用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 } ]

谢谢:)

5 个答案:

答案 0 :(得分:67)

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

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

答案 1 :(得分:20)

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

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

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

答案 2 :(得分:1)

我认为与MySQLdb相比,使用mysql.connector将选择转换为字典要容易得多,并且还支持更多的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"]

答案 3 :(得分:0)

这是一篇古老的文章,虽然这个答案并不完全是OP所寻求的,但它的内容大致相同。它不是生成字典列表,而是生成列表字典:

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        for (int i = 0; i != 5; i++) {
            Bundle args = new Bundle();
            args.putString("text", "success" + i);

            ActivityFragment myFragment = new ActivityFragment();
            myFragment.setArguments(args);

            getFragmentManager().beginTransaction()
                                .add(R.id.fragment_container, myFragment).commit();
        }
    }

    public static class ActivityFragment extends Fragment {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, Bundle savedInstanceState) {
            final View fragment1 = inflater.inflate(R.layout.activity_fragment, container, false);

            final TextView activityText = (TextView) fragment1.findViewById(R.id.activity_text);
            String text = getArguments().getString("text");
            activityText.setText(text);

            return fragment1;
        }
    }
}

哪个收益率:

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 }

答案 4 :(得分:0)

使用PYTHON> = 3.6;在这里它通过以下方式起作用:

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

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

myp3 ='XXXXXXXXXXXXXXXXXXXXXXXXXX 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)

“”“