0
我有一个我正在尝试放入mysql的excel文件。有32个字段,我想使用python插件xlrd提取并放入mysql中。该数据布局,像这样:Mysqldb INSERT INTO Python中的语法错误
我的方法是迭代的行和列,添加字段名,我去。该代码添加字段名称,但添加数据时出现错误。 (我有一个指数作为唯一的场创建的表 'OilProvedReservesHistory'):
def get_data_from_sheet(sheet_index, table, start_row, end_row, end_col):
for row in range(start_row - 1, end_row - 1):
for col in range(end_col):
cell = sheet.cell(row,col)
if col == 0:
fieldname = cleanup_field(cell.value)
if fieldname != ("Blank Cell"):
sql = "ALTER TABLE OilProvedReservesHistory ADD %s VARCHAR(20)" % fieldname
c.execute(sql)
else:
data = cleanup_data(cell)
if data != ("Blank Cell"):
postToMySQL(data,fieldname,table)
def postToMySQL(data,fieldname,table):
#Generate sql query string
sql = "INSERT INTO " + table + " ("+ fieldname + ") VALUES %s"
c.execute(sql, data)
# Executes: ("""INSERT INTO OilProvedReservesHistory (US) VALUES 36.533""")
table = create_table_from_sheet_name()
sheet_index = 0
start_row = 5
end_row = 68
end_col = 32
get_data_from_sheet(sheet_index, table, start_row, end_row, end_col)
我得到的错误是:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''36.533'' at line 1")
你能帮我得到这个工作?非常感谢!
哈,是啊,你说得对!在我发布之前,我一直试图创建所有字段名,然后发布数据值,但我认为错误是我试图用一个值填充行。谢谢! – user578582
不客气。 –