我将.xls文件中的特定数据转储到mysql数据库.虽然尝试我得到以下错误.
我的.py文件
import xlrd
import MySQLdb
book = xlrd.open_workbook("Sheet2.xls")
sheet = book.sheet_by_name("Sheet1")
database = MySQLdb.connect (host="localhost", user="root", passwd="", db="dtz_new")
cursor = database.cursor()
query = """INSERT INTO property_property(name) VALUES(%s)"""
for r in range(1, sheet.nrows):
gaurav = sheet.cell(r,1).value
values = (gaurav)
cursor.execute(query, values)
cursor.close()
database.commit()
database.close()
print "all done, Bye for now"
columns = str(sheet.ncols)
rows = str(sheet.nrows)
print "I just imported "+ columns+ " columns and "+ rows+" rows to MySQL!"
Run Code Online (Sandbox Code Playgroud)
我得到的错误就在这里
Traceback (most recent call last):
File "dtz_db.py", line 29, in <module>
cursor.execute(query, values)
File "c:\Python27\lib\site-packages\MySQLdb\cursors.py", line 187, in execute
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
Run Code Online (Sandbox Code Playgroud)
单元格(1,1)值是Kunjvihar它在python中的名字charfield请帮我解决这个问题
你需要做values
一个实际的元组:
values = (gaurav,)
Run Code Online (Sandbox Code Playgroud)
注意那里的逗号 ; 只是括号只用于对表达式进行分组,它是将表达式定义为元组的逗号.
没有逗号,您只有一个字符串值,也是一个序列.MySQL然后尝试仅插入单个字符,并且您的字符串值中有多个字符.使用额外字符会抛出异常.