[英]Python MySQLdb for CSV import into MySQL table with more columns than CSV / list idx out of range?
[英]Python: use mysqldb to import a MySQL table as a 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 } ]
謝謝 :)
MySQLdb有一個單獨的游標類,DictCursor。 您可以將要使用的游標類傳遞給MySQLdb.connect():
import MySQLdb.cursors
MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)
如果你需要使用更多的游標,只需要一個是MySQLdb.cursors.DictCursor,你可以這樣做:
import MySQLdb
db = MySQLdb.connect(host='...', db='...', user='...t', passwd='...')
list_cursor = db.cursor()
dict_cursor = db.cursor(MySQLdb.cursors.DictCursor)
我認為使用mysql.connector將select轉換為dict比MySQLdb更容易,並且支持更多的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"]
這是一個古老的帖子,雖然這個答案並不完全是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'] }
使用PYTHON> = 3.6; 這是通過這樣做:
OBS:這里我使用的是2種數據庫類型ORACLE 12g和MYSQL 5.6; 並且主服務器是ORACLE,mysql僅由軟件的某些部分使用...然后...我的連接類的代碼:
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)
“””
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.