从python插入时,我遇到了一个“必须声明标量变量”错误

2024-10-01 22:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码。我正在尝试将CSV中的数据插入SQL Server表。我试图遵循一个相对简单的例子: https://datatofish.com/import-csv-sql-server-python/

import pandas as pd
import pyodbc

data = pd.read_csv(r'C:\Users\Steve\Documents\Datasets\covidgeography.csv')
df = pd.DataFrame(data, columns=['MMSA', 'total_percent_at_risk', 'high_risk_per_ICU_bed', 'high_risk_per_hospital',
                                 'icu_beds', 'hospitals', 'total_at_risk'])
print(df)

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=STEVELAPTOP;'
                      'Database=AdventureWorks2017;'
                      'Trusted_Connection=yes;')
cursor = conn.cursor()

#cursor.execute('CREATE TABLE dbo.covidgeo(MMSA nvarchar(250),total_percent_at_risk nvarchar(250),'
#               'high_risk_per_ICU_bed nvarchar(250), '
#               'high_risk_per_hospital nvarchar(250),icu_beds nvarchar(250),hospitals nvarchar(250),total_at_risk '
#               'nvarchar(250))')
for row in df.itertuples():
    cursor.execute('''INSERT INTO AdventureWorks2017.dbo.covidgeo(MMSA,total_percent_at_risk,high_risk_per_ICU_bed,
    high_risk_per_hospital,icu_beds,hospitals,total_at_risk) VALUES (???????) 
    ''',
                   row.MMSA,
                   row.total_percent_at_risk,
                   row.high_risk_per_ICU_bed,
                   row.high_risk_per_hospital,
                   row.icu_beds,
                   row.hospitals,
                   row.total_at_risk)
    conn.commit()


运行此命令后,出现以下错误:

Traceback (most recent call last):
  File "C:\Users\Steve\PycharmProjects\DataLearning\DataImport.py", line 20, in <module>
    cursor.execute('''INSERT INTO AdventureWorks2017.dbo.covidgeo(MMSA,total_percent_at_risk,high_risk_per_ICU_bed,
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Must declare the scalar variable "@P1@P2@P3@P4@P5@P6@P7". (137) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)')

我在编写insert语句时是否有语法错误


Tags: sqlservercursoratrowtotalriskbed

热门问题