You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改Python脚本实现Excel导入SQL Server时校验卡号唯一性

带Card字段存在性校验的SQL Server数据导入脚本

以下是修改后的完整脚本,实现了仅导入数据库中不存在的Card记录的功能:

import pandas as pd
import pyodbc

# 创建数据库连接
conn = pyodbc.connect(
    "Driver={SQL Server Native Client 11.0};"
    "Server=DESKTOP-4JP7FB3;"
    "Database=convert;"
    "Trusted_Connection=yes;"
)
cursor = conn.cursor()

# 创建orders表(仅当表不存在时执行)
create_table_query = """
CREATE TABLE orders (
    Name varchar(255),
    Serial INT,
    Date varchar(255),
    Price INT,
    Card INT
)
"""
try:
    cursor.execute(create_table_query)
    conn.commit()
except pyodbc.ProgrammingError:
    pass  # 表已存在时跳过执行

# 预加载数据库中已存在的Card值,存入集合(提升查询效率)
cursor.execute("SELECT Card FROM orders")
existing_cards = {row[0] for row in cursor.fetchall()}

# 读取Excel数据
df = pd.read_excel('C:/Users/Administrator/Desktop/MyExcell/convert/daramad.xls', sheet_name="source")

# 记录导入前的表行数
cursor.execute("SELECT count(*) FROM orders")
before_import = cursor.fetchone()[0]

# 定义插入语句
insert_query = """
INSERT INTO orders (Name, Serial, Date, Price, Card)
VALUES (?, ?, ?, ?, ?)
"""

import_count = 0
# 遍历数据,仅导入Card不存在的记录
for _, row in df.iterrows():
    current_card = row['Card']
    if current_card not in existing_cards:
        # 组装插入参数
        values = (row['Name'], row['Serial'], row['Date'], row['Price'], current_card)
        cursor.execute(insert_query, values)
        import_count += 1
        existing_cards.add(current_card)  # 更新集合,避免后续重复判断

# 提交所有插入操作
conn.commit()

# 验证导入结果
cursor.execute("SELECT count(*) FROM orders")
after_import = cursor.fetchone()[0]

print(f"实际成功导入 {import_count} 条新记录")
print(f"导入行数验证:{(after_import - before_import) == import_count}")

# 关闭数据库资源
cursor.close()
conn.close()

print("\nAll Done! Bye, for now.\n")
print(f"读取的Excel数据包含 {df.shape[1]} 列,{df.shape[0]} 行")

关键修改说明

  1. 预加载已存在的Card集合

    • 提前查询数据库中所有已有的Card值,存入集合existing_cards。集合的成员查询效率远高于每次插入前单独查询数据库,能大幅提升脚本运行速度。
  2. 添加存在性校验逻辑

    • 遍历Excel每行数据时,先判断当前Card是否不在已存在集合中,仅满足条件的记录才执行插入操作。插入成功后将该卡号加入集合,避免后续重复判断。
  3. 简化数据读取逻辑

    • 移除冗余的xlrd操作,统一使用pandas读取Excel数据,代码更简洁易维护。
  4. 优化事务与资源管理

    • 所有插入操作完成后统一提交事务,避免频繁提交带来的性能损耗;同时确保游标和数据库连接正确关闭,避免资源泄漏。

内容的提问来源于stack exchange,提问作者babak gh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:04:53