python - 使用 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()
你能指导我解决这个问题吗?
解决方案
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()
推荐阅读
- tensorflow - tf.nn.conv2d_transpose 和 slim.conv2d_transpose 的区别
- c# - WPF 在运行时使用“Validation.HasError”作为路径添加边距绑定
- java - 解组空 xml 元素 jaxb
- xamarin - 如何将自动填充设置为网格列宽
- ruby-on-rails - 请求中包含的安全令牌无效。Aws::SQS::Errors::InvalidClientTokenId
- authorization - Google 电子表格 - 从 PHP 表单存储数据
- cordova - 当我上传 zip 文件时,phonegap 构建失败
- blockchain - 运行区块链网络的成本
- amazon-web-services - AWS 负载均衡器到 nginx
- python - 消除python中非方阵的线性相关列