首页 > 解决方案 > 使用 python 上传数据时未在 SQL Server 上创建表

问题描述

我是使用python连接sql server的新手。我需要从sql server读取一些数据进行处理并将处理后的数据上传到sql server。所有这些任务都将使用python完成。所以我已经编写了从 sql server 中提取数据的代码,进行了处理,最后当我尝试在 sql server 上上传数据时,我的代码工作正常,我没有从 python 收到任何错误消息。但是我'无法在 SQL Server 上看到表,即使我尝试使用我的 python 代码从 sql server 检索数据,我也会收到错误消息

 pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'output1'. (208) (SQLExecDirectW)")

下面是我用来将数据插入到 sql server 的代码

  conn = sqlite3.connect('Driver={SQL Server};'
                                'Server=My server name;'
                                'Database=my data base name;'
                                'uid=my uid;pwd=my password')
c=conn.cursor()
date = dt.datetime.today().strftime("%m/%d/%Y")
dataToUpload['OPT_TYPE']=opt_type
dataToUpload['Date']=date
list_opt_output=dataToUpload.values.tolist()

c.execute('''CREATE TABLE if not exists output1
         (Class text,Location text,Name text,Maths decimal(5,2), nonMaths decimal(5,2), promopercent decimal(5,3),OPT_TYPE text,Date date)''')
conn.commit()
print("Output table created")
c.executemany('''INSERT INTO output1(Class,Location,Name,Maths, nonMaths,promopercent,OPT_TYPE,Date) VALUES (?,?,?,?,?,?,?,?)''', list_opt_output)

conn.commit()
conn.close()

你能指导我解决这个问题吗?

标签: pythonsql-server

解决方案


CREATE TABLE if not exists output1不是有效的SQL Server语法。您可以使用IF OBJECT_ID('output1','U') IS NULL检查表是否存在。

更改您的查询,如下所示。

c.execute('''IF OBJECT_ID(''output1'',''U'') IS NULL CREATE TABLE output1
         (Class text,Location text,Name text,Maths decimal(5,2), nonMaths decimal(5,2), promopercent decimal(5,3),OPT_TYPE text,Date date)''')
conn.commit()

推荐阅读