【问题标题】:Exporting specific MySQL data from table to Excel using Python使用 Python 将特定 MySQL 数据从表导出到 Excel
【发布时间】:2016-03-17 14:59:39
【问题描述】:

我对 mysql-connector-python 还很陌生。我正在学习如何使用 python 让我的工作更轻松一些。能否请你帮忙?

我有一个带有一个表的数据库。我们称它为“table1”。该表按如下所示的列进行细分:

sent_time | delivered_time |id1_active |id2_active |id3_active |id1_inactive |id2_inactive |id3_inactive |location_active |location_inactive .....`还有很多

假设这是两个或多个客户相互运送货物。每个客户都有三个 id#。

现在我想看看我是否至少可以为所有这些打印出 id1_active 和 id2_active...理想情况下,我想打印任何列中提到的具有特定 id 的整行...你能看看下面看看我做错了什么,也许可以帮助我找到实现理想目标的解决方案?

我不断收到此错误

第 18 行,在 c.writerow([id1_active,id2_active])

TypeError: ‘str’ 不支持缓冲区接口

这是我迄今为止所拥有的……

我创建了一个“config.ini”文件让我的生活更轻松

[mysql]
host = localhost
database = db_name
user = root
password = blahblah

我创建了一个“python_mysql_dbconfig.py”

from configparser import ConfigParser

def read_db_config(filename=’config.ini’, section=’mysql’):
“”” Read database configuration file and return a dictionary object
:param filename: name of the configuration file
:param section: section of database configuration
:return: a dictionary of database parameters
“””
# create parser and read ini configuration file
parser = ConfigParser()
parser.read(filename)

# get section, default to mysql
db = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
db[item[0]] = item[1]
else:
raise Exception(‘{0} not found in the {1} file’.format(section, filename))

return db

然后我创建了“export.py”

from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
import csv

filename=open(‘test.csv’,’wb’)
c=csv.writer(filename)

db_config = read_db_config()
conn = MySQLConnection(**db_config)
cursor = conn.cursor()

query = (“SELECT id1_active, id2_active from table1”)

cursor.execute(query)

for id1_active, id2_active in cursor:
c.writerow([id1_active,id2_active] )

cursor.close()
filename.close()
cnn.close()

你能告诉我我做错了什么吗?

【问题讨论】:

    标签: python mysql excel csv export


    【解决方案1】:

    你需要获取数据并循环遍历数据而不是游标:

    from mysql.connector import MySQLConnection, Error
    from python_mysql_dbconfig import read_db_config
    import csv
    
    filename=open(‘test.csv’,’wb’)
    c=csv.writer(filename)
    
    db_config = read_db_config()
    conn = MySQLConnection(**db_config)
    cursor = conn.cursor()
    
    query = (“SELECT id1_active, id2_active from table1”)
    
    cursor.execute(query)
    
    #You first need to fetch data
    data = cursor.fetchall()
    for item in data:
        c.writerow(item )
    
    cursor.close()
    filename.close()
    cnn.close()
    

    【讨论】:

    • 我开始搞乱 xlsxwriter 并且实际上我自己更进一步......你能看看我的代码,看看为什么我不能选择要在两个日期时间之间导出的数据吗?
    【解决方案2】:

    我开始使用 xlswriter 解决问题。我能够从表中导出所有数据,但现在我无法让我的代码提取两个日期时间之间的数据......它一直在告诉我

        Traceback (most recent call last):
      File "C:\Python34\timerange.py", line 36, in <module>
        start_date = datetime.datetime(userIn,timeShape)
    AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
    

    拜托,你能告诉我我做错了什么吗?

    # Establish a MySQL connection
    from mysql.connector import MySQLConnection, Error
    from python_mysql_dbconfig import read_db_config
    db_config = read_db_config()
    conn = MySQLConnection(**db_config)
    import xlsxwriter
    from xlsxwriter.workbook import Workbook
    import datetime
    from datetime import datetime
    cursor = conn.cursor()
    
    #creates the workbook
    workbook = xlsxwriter.Workbook('imhere.xlsx')
    worksheet = workbook.add_worksheet()
    
    #formatting definitions
    bold    = workbook.add_format({'bold': True})
    date_format = workbook.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'})
    timeShape =  '%Y-%m-%d %H:%M:%S'
    
    
    
    query = ("SELECT sent_time, delivered_time, customer_name, id1_active, id2_active, id3_active, id1_inactive, id2_inactive, id3_inactive, location_active, location_inactive FROM table1 ")
    "WHERE sent_time BETWEEN %s AND %s"
    userIn = input("Type Start Date (YYYY-MM-DD hh:mm:ss):")
    userEnd = input("Type End Date (YYYY-MM-DD hh:mm:ss):")
    start_date = datetime.datetime(userIn,timeShape)
    end_date = datetime.datetime(userEnd, timeShape)
    
    
    
    # Execute sql Query
    cursor.execute(query, (start_date, end_date))
    #result = cursor.fetchall()
    
    
    #sets up the header row
    worksheet.write('A1','sent_time',bold)
    worksheet.write('B1', 'delivered_time',bold)
    worksheet.write('C1', 'customer_name',bold)
    worksheet.write('D1', 'id1_active',bold)
    worksheet.write('E1', 'id2_active',bold)
    worksheet.write('F1', 'id3_active',bold)
    worksheet.write('G1', 'id1_inactive',bold)
    worksheet.write('H1', 'id2_inactive',bold)
    worksheet.write('I1', 'id3_inactive',bold)
    worksheet.write('J1', 'location_active',bold)
    worksheet.write('K1', 'location_inactive',bold)
    worksheet.autofilter('A1:K1')
    
    
    
    print("sent_time", "delivered_time", "customer_name", "id1_active", "id2_active", "id3_active", "id1_inactive", "id2_inactive", "id3_inactive", "location_active", "location_inactive")
    for row in cursor:
        print(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10])
    
    # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
    for r, row in enumerate(cursor, start=1):  #where you want to start printing results inside workbook
        for c, col in enumerate(row):
            worksheet.write_datetime(r,0,row[0], date_format)
            worksheet.write_datetime(r,1, row[1], date_format)
            worksheet.write(r,2, row[2])
            worksheet.write(r,3, row[3])
            worksheet.write(r,4, row[4])
            worksheet.write(r,5, row[5])
            worksheet.write(r,6, row[6])
            worksheet.write(r,7, row[7])
            worksheet.write(r,8, row[8])
            worksheet.write(r,9, row[9])
            worksheet.write(r,10, row[10])
    
    
    
    
    #close out everything and save
    cursor.close()
    workbook.close()
    conn.close()
    
    #print number of rows and bye-bye message
    print ("- - - - - - - - - - - - -")
    rows = len(result)
    print ("I just imported "+ str(rows) + " rows from MySQL!")
    print ("")
    print ("Good to Go!!!")
    print ("")
    

    【讨论】:

      猜你喜欢
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-06-17
      相关资源
      最近更新 更多