简体   繁体   English

SQL 服务器如何更新如果存在否则由 Python 插入

[英]SQL Server how to UPDATE if exists else INSERT by Python

I've searched many articles in stack overflow but not able to find one meeting my requirement.我在堆栈溢出中搜索了许多文章,但找不到满足我要求的文章。 Below is what I'm referring to.以下是我所指的。

UPDATE if exists else INSERT in SQL Server 2008 更新如果存在,否则在 SQL 服务器 2008 中插入

My requirement Using Python to create an ETL procedure: extract data from a source, transform to a dataframe then upload to MS SQL Server.我的要求使用 Python 创建 ETL 过程:从源中提取数据,转换为 dataframe 然后上传到 MS SQL 服务器。 If a duplicate row with same product_id is found, then UPDATE SQL database otherwise INSERT a new row.如果找到具有相同 product_id 的重复行,则更新 SQL 数据库,否则插入新行。

My Code我的代码

import pandas as pd
import pyodbc

# Import CSV
data = pd.read_csv(r'C:\Users\...\product.csv')
df = pd.DataFrame(data)
records = df.values.tolist()

# Connect to SQL Server
server = 'AAABBBCCC\SQLEXPRESS' 
database = 'abcdefg' 
username = 'User' 
password = '' 
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=True;')
cursor = cnxn.cursor()

#Insert Data
sql_insert = '''
    UPDATE [atetestdb].[dbo].[products] 
    SET product_name = ?
    ,price = ?
    WHERE product_id = ?

    IF @@ROWCOUNT = 0
        INSERT INTO [atetestdb].[dbo].[products] 
            (product_id, product_name, price)
        VALUES (?, ?, ?)
'''

cursor.executemany(sql_insert, records)

cnxn.commit()

My Result The error message I got:我的结果我得到的错误信息:

The SQL contains 6 parameter markers, but 3 parameters were supplied SQL 包含 6 个参数标记,但提供了 3 个参数

It seems something wrong with the SQL comment. SQL 评论似乎有问题。 Could someone help?有人可以帮忙吗? Any other solution to meet my requirement is also appreciated.任何其他满足我要求的解决方案也值得赞赏。

My Dataset in SQL database我在 SQL 数据库中的数据集

product_id product_id product_name产品名称 price价格
1 1 Desk桌子 1900 1900
2 2 Printer打印机 200 200
3 3 Tablet药片 350 350
4 4 Keyboard键盘 80 80
5 5 Monitor监视器 1200 1200
6 6 Desk桌子 900 900

My Dataset in csv file csv 文件中的我的数据集

product_id product_id product_name产品名称 price价格
5 5 Monitor监视器 600 600

Change the batch to have local variables for each parameter, eg:将批次更改为每个参数都有局部变量,例如:

sql_insert = '''
    declare @product_name varchar(100) = ?
    declare @price decimal(10,2) = ?
    declare @product_id int = ?

    UPDATE [atetestdb].[dbo].[products] 
    SET product_name = @product_name, price = @price
    WHERE product_id = @product_id

    IF @@ROWCOUNT = 0
        INSERT INTO [atetestdb].[dbo].[products] 
            (product_id, product_name, price)
        VALUES (@product_id, @product_name, @price)
'''

You can go for simple MERGE statement.您可以 go 进行简单的 MERGE 语句。

MERGE [atetestdb].[dbo].[products] as t
USING (Values(?,?,?)) AS s(Product_name, price, product_id)
ON tgr.product_id = src.product_id 
WHEN MATCHED THEN UPDATE SET 
         t.product_name = s.product_name
    ,t.price = s.price
WHEN NOT MATCHED BY TARGET 
    THEN INSERT (Product_name, price, product_id)
         VALUES (s.Product_name, s.price, s.product_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM