Mysqldb在Python中INSERT INTO语法错误

时间:2012-05-07 14:53:48

标签: python sql syntax-error mysql-python

我有一个excel文件,我试图将其放入mysql。我想用python插件xlrd提取32个字段并放入mysql。数据的布局如下:

Data Layout

我的方法是迭代行和列,随时添加字段名。代码添加了字段名称,但添加数据时出错。 (我创建了表'OilProvedReservesHistory',索引为唯一字段):

SQL Layout

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,“您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以便在第1行''36 .533'附近使用正确的语法”

你能帮我搞定吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

我猜你只是忘记了VALUES子句的括号。

INSERT INTO OilProvedReservesHistory (US) VALUES (36.533)

尝试将代码更改为:

sql = "INSERT INTO " + table + " ("+ fieldname + ") VALUES (%s)"