我目前正在嘗試使用pyodbc將數據從.csv插入到Azure SQL Server數據庫中。我在堆棧溢出中找到了這個語法的大部分,然而由於某種原因,我總是收到兩個不同的錯誤之一。Python PYDOBC插入帶有參數的SQL Server數據庫
1)每當我使用下面的代碼,我得到一個錯誤,指出'SQL包含0個參數標記,但提供了7個參數'。
import pyodbc
import csv
cnxn = pyodbc.connect('driver', user='username', password='password', database='database')
cnxn.autocommit = True
cursor = cnxn.cursor()
csvfile = open('CSV File')
csv_data = csv.reader(csvfile)
SQL="insert into table([Col1],[Col2],[Col3],[Col4],[Col5],[Col6],[Col7]) values ('?','?','?','?','?','?','?')"
for row in csv_data:
cursor.execute(SQL, row)
time.sleep(1)
cnxn.commit()
cnxn.close()
2)爲了擺脫這個錯誤,我通過添加'=?'來定義參數標記。到插入語句中的每個列(請參閱下面的代碼),然而這會給出以下錯誤:ProgrammingError:('42000'「[42000] [Microsoft] [ODBC SQL Server驅動程序] [SQL Server]語法附近' =')。
import pyodbc
import csv
cnxn = pyodbc.connect('driver', user='username', password='password', database='database')
cnxn.autocommit = True
cursor = cnxn.cursor()
csvfile = open('CSV File')
csv_data = csv.reader(csvfile)
SQL="insert into table([Col1]=?,[Col2]=?,[Col3]=?,[Col4]=?,[Col5]=?,[Col6]=?,[Col7]=?) values ('?','?','?','?','?','?','?')"
for row in csv_data:
cursor.execute(SQL, row)
time.sleep(1)
cnxn.commit()
cnxn.close()
這是我用,我已經找遍了堆棧溢出,似乎無法找到解決辦法的麻煩巡航能力的主要錯誤。我知道這個錯誤可能是很瑣碎,但是我是新來的Python和將不勝感激的任何建議或幫助。
真棒,那工作的感謝! – ls101