Python采集学习笔记-SQL Server不同表的数据转移

(同一数据库表数据转移)源码

python 复制代码
import pyodbc

# 连接数据库
server = 'DESKTOP-HAI1BEH'
database = 'T1'
driver = '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect(f'DRIVER={driver};SERVER={server};DATABASE={database};Trusted_Connection=yes;')
# 查询数据
cursor = conn.cursor()
cursor.execute('select top 3 * from emp')

# 获取查询结果
results = cursor.fetchall()
for result in results:
    # 插入方法1
    # cursor.execute('insert into emp_copy (id,name,password,date) values(?,?,?,?)',result.id,result.name,result.password,result.date)
    # 插入方法2
    cursor.execute(f"insert into emp_copy (id,name,password,date) values('{result[0]}','{result[1]}','{result[2]}','{result[3]}')")
conn.commit()
print("数据插入成功!")
# 关闭游标和连接
cursor.close()
conn.close()

(不同数据库表数据转移)源码

python 复制代码
import pyodbc

# 连接源数据库
source_conn_str = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=DESKTOP-HAI1BEH;DATABASE=T1;UID=sa;PWD=pwd_Admin'
source_conn = pyodbc.connect(source_conn_str)
source_cursor = source_conn.cursor()
print('source连接成功')

# 连接目标数据库
target_conn_str = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=DESKTOP-HAI1BEH;DATABASE=T2;UID=sa;PWD=pwd_Admin'
target_conn = pyodbc.connect(target_conn_str)
target_cursor = target_conn.cursor()
print('target连接成功')
try:
    # 查询源数据库的T1表emp前10条数据
    source_cursor.execute('SELECT TOP 10 * FROM T1.dbo.emp')
    rows = source_cursor.fetchall()

    # 插入数据到目标数据库T2的emp表中
    for row in rows:
        target_cursor.execute("INSERT INTO T2.dbo.emp VALUES (?, ?, ?, ?)", row.id, row.name, row[2], row[3])

    # 提交事务
    target_conn.commit()
    print("数据插入成功!")

except Exception as e:
    # 发生异常时回滚事务
    target_conn.rollback()
    print("数据插入失败:", str(e))

finally:
    # 关闭连接
    source_cursor.close()
    source_conn.close()
    target_cursor.close()
    target_conn.close()
相关推荐
qq_158895411112 小时前
Suno-API 是什么?官方 V6 模型与 Python / TypeScript 接入指南
python·ai音乐·suno api
学无止境小袁同学13 小时前
Google ADK 学习指南
python·llm·agent·多agent·google adk·llmagent·agent cli
郝学胜-神的一滴13 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
LK_0714 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
wuyk55514 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
一条破秋裤14 小时前
【1115】【多线程】【笔记】
前端·chrome·笔记
神明不懂浪漫14 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记
用户548178459095015 小时前
Java 与 Python 在大模型与智能体领域的选型
java·python
yiangL_15 小时前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互