参数化INSERT查询的这种语法有什么问题?

时间:2015-01-07 17:14:40

标签: excel python-2.7 ms-access-2007 xlrd comtypes

我正在尝试将Excel数据导入MS-access数据库,但是它给了我'语法错误定义'

代码:

for col_index in range(0,work_sheet.ncols):
    column_value = work_sheet.cell(0,col_index).value
    for row_index in range(1, work_sheet.nrows):
        row_value = work_sheet.cell(row_index,col_index).value # For the same column, fetch the row data repeatedly
        db.Execute("INSERT INTO my_table" [column_value] "VALUES(" & row_value & ")")

错误:

C:\Data\Database>c:\python27\python.exe My_First_DB_Code.py
File "My_First_DB_Code.py", line 32
db.Execute("INSERT INTO my_table" [column_value] "VALUES(" & row_value & ")")

SyntaxError: invalid syntax

注意:我已经从Excel工作表导入了列名,现在尝试逐列导入行值

1 个答案:

答案 0 :(得分:2)

您需要使用Python的字符串连接语法,而不是SQL。尝试单独生成SQL字符串,然后打印它以确保在进行数据库调用之前它是正确的:

query_string = "INSERT INTO my_table" + str(column_value) + " VALUES( " + str(row_value) + " )"
print(query_string)
# db.Execute(query_string)
# uncomment when you know the query is correct

上面的代码假定您要连接my_tablecolumn_value,它们之间没有空格。如果您正在尝试输入字段名称作为HansUp comments,请设置query_string,如下所示:

query_string = query_string = "INSERT INTO my_table ([" + str(column_value) + "]) VALUES ('" + str(row_value) + "')"