【发布时间】: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