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

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

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()

 

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

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()

 

你可能感兴趣的:(python,学习,笔记)