【发布时间】:2021-07-27 12:24:26
【问题描述】:
我有一个不断增长和变化的数据库,它反映了州和 EPA 通过的许可。 随着数据库的变化和更新,我需要传输相关信息。
脚本做了两件事;首先它检查哪些字段是相同的,并创建一个字段和数据列表,这些字段和数据将被插入到新数据库中。其次将数据插入到新的数据库中。
问题是我无法插入它。我已经以各种方式匹配了网上所说的所有内容,但出现错误('42000'、'[42000] [Microsoft][ODBC Microsoft Access Driver] INSERT INTO 语句中的语法错误。(-3502)(SQLExecDirectW)')。
我不知道如何防止它。
代码:
import pyodbc
importDatabase = r"J:\ENVIRO FIELD\AccessDatabases\MS4\MS4 Town Databases\~Template\MS4_Apocalypse Import DEV 1.accdb"
"Create the Import Database Connection"
connectionImport = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;' %(importDatabase))
cursorImport = connectionImport.cursor()
"####---Outfall Section---####"
"Import the outfall names into the new database"
tbl = "tbl_Outfall_1_Profile"
exportList = []
importList = []
for row in cursorImport.columns(table = "tblExportMigration_Outfall_1_Profile"):
field = row.column_name
exportList.append(field)
for row in cursorImport.columns(table = "tbl_Outfall_1_Profile"):
field = row.column_name
importList.append(field)
matchingList = []
for field in exportList:
if field != "outfallID":
if field in importList:
matchingList.append(field)
else:
continue
sqlValue = ""
for field in matchingList:
sqlValue += "[%s], " %(field)
sqlValue = sqlValue[:-2]
sql = "SELECT %s from %s" %(sqlValue, "tblExportMigration_Outfall_1_Profile")
for rowA in cursorImport.execute(sql):
tupleList = list(rowA)
tupleList = ["" if i == None else i for i in tupleList]
tupleValues = tuple(tupleList)
sqlUpdate = """INSERT INTO tbl_Outfall_1_Profile (%s) Values %s;""" %(sqlValue, tupleValues)
cursorImport.execute(sqlUpdate)
cursorImport.close()
这是我创建的 sql 字符串
“插入到 tbl_Outfall_1_Profile([profile_OutfallName]、[profile_HistoricalName1]、[profile_HistoricalName2]、[profile_HistoricalName3]、[profile_HistoricalName4])值('756'、''、''、''、'');”
【问题讨论】:
-
首先,不要使用字符串替换(“动态 SQL”)来插入列值。请改用正确的参数化查询,例如
sqlUpdate = "INSERT INTO tbl_name (col1, col2) Values (?, ?);",后跟cursorImport.execute(sqlUpdate, (param1, param2))。在网络上搜索“小鲍比桌”以获取更多信息。 -
@GordThompson 我不能将信息硬连接到查询中。我可以创建一段脚本来生成?但是,由于许可证的性质,表格字段名称很有可能被更新和更改。我必须在系统中解决这个问题,否则以后会出现问题。我没有创建也没有写许可证,但我必须让系统反映它。
-
因此您可能仍需要对列列表使用动态 SQL,因为参数替换仅适用于列 values,而不适用于列 names,但您仍然应该为值使用参数。
-
@GordThompson 这就是您要执行的操作:sqlUpdate = "INSERT INTO tbl_Outfall_1_Profile ([profile_OutfallName], [profile_HistoricalName1], [profile_HistoricalName2], [profile_HistoricalName3], [profile_HistoricalName4]) 值 (? ,?,?,?,?);" cursorImport.execute(sqlUpdate, (tupleValues))
-
就是这样,是的。
标签: python python-3.x python-2.7 ms-access pyodbc