import xlsxwriter
import MySQLdb as mdb
import sys
reload(sys)
sys.setdefaultencoding('Cp1252')
first = "jim"
last = "bob"
# Initiate MySQL connection.
con = mdb.connect(unix_socket = '/var/lib/mysqld/mysqld.sock', host = 'localhost', user = 'timmy', passwd = '123America', db = 'southend');
cur = con.cursor()
query = "SELECT user_id from users where first like %s and last like %s"
# Execute MySQL query.
cur.execute(query,("%" + first + "%", "%" + last + "%"))
# Gather query results.
rows = cur.fetchall()
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('like_test.xlsx')
worksheet = workbook.add_worksheet()
# Add headers for our worksheet data.
worksheet.write('A1','User ID')
# Start from the first cell. Rows and columns are zero indexed.
row = 1
col = 0
# Iterate over the data and write it out row by row.
for user_id in (rows):
worksheet.write(row, col, user_id)
row += 1
workbook.close()
con.close()
以下是运行程序时出现的错误:
Traceback (most recent call last):
File "test.py", line 35, in <module>
worksheet.write(row, col, user_id)
File "/usr/lib/python2.6/site-packages/xlsxwriter/worksheet.py", line 64, in cell_wrapper
return method(self, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/xlsxwriter/worksheet.py", line 431, in write
raise TypeError("Unsupported type %s in write()" % type(token))
TypeError: Unsupported type <type 'tuple'> in write()
Exception Exception: Exception('Exception caught in workbook destructor. Explicit close() may be required for workbook.',) in <bound method Workbook.__del__ of <xlsxwriter.workbook.Workbook object at 0x1a37e90>> ignored
我对python并不熟悉 - 我主要只是开始阶段,他们调用MySQL的方式对我来说很不寻常。有什么帮助吗?
由于我使用变量,我想我被迫使用&#39;%s&#39;脚本中的选项。
答案 0 :(得分:2)
cur.fetchall()
返回每行的列值列表。
即使您只获取一个列值,它仍会为每一行返回一个列表..每行包含一个值。
所以:
for row in rows:
worksheet.write(row, col, row[0])
rows
是一个行列表,每个row
都是该行的值列表。