Python采集学习笔记-SQL Server数据转移到MySQL

 未封装函数版本

import pyodbc
import mysql.connector

# SQL Server数据库连接配置
sql_server_connection_string = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=DESKTOP-HAI1BEH;DATABASE=T1;UID=sa;PWD=pwd_Admin'

# MySQL数据库连接配置
mysql_connection_config = {
    'user': 'root',
    'password': 'pwd_Admin',
    'host': 'localhost',
    'database': 'test',
}

# 连接SQL Server数据库
sql_server_conn = pyodbc.connect(sql_server_connection_string)
sql_server_cursor = sql_server_conn.cursor()

# 连接MySQL数据库
mysql_conn = mysql.connector.connect(**mysql_connection_config)
mysql_cursor = mysql_conn.cursor()

try:
    # 从SQL Server中获取数据
    sql_server_cursor.execute("SELECT id, name, password, date FROM emp")
    rows = sql_server_cursor.fetchall()

    # 将数据插入到MySQL的emp_copy表中
    for row in rows:
        id = row[0]
        name = row[1]
        password = row[2]
        date = row[3]
        mysql_cursor.execute("INSERT INTO emp_copy (id, name, password, date) VALUES (%s, %s, %s, %s)", (id, name, password,date))

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

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

finally:
    # 关闭数据库连接
    sql_server_cursor.close()
    sql_server_conn.close()
    mysql_cursor.close()
    mysql_conn.close()

 封装函数版本源码

import pyodbc
import mysql.connector


def connect_sql_server(driver, server, database, username, password):
    conn = pyodbc.connect(
        driver=driver,
        server=server,
        database=database,
        uid=username,
        pwd=password
    )
    return conn


def connect_mysql(host, user, password, database):
    conn = mysql.connector.connect(
        host=host,
        user=user,
        password=password,
        database=database
    )
    return conn


def fetch_data_sql_server(conn, table, limit):
    cursor = conn.cursor()
    try:
        query = f"SELECT id, name, password, date FROM {table}"
        cursor.execute(query)
        result = cursor.fetchall()
        return result
    except pyodbc.Error as error:
        print("数据读取失败: {}".format(error))


def insert_data_mysql(conn, data, table):
    cursor = conn.cursor()
    try:
        # 构建插入语句
        for row in data:
            id = row[0]
            name = row[1]
            password = row[2]
            date = row[3]
            cursor.execute(f"INSERT INTO {table} (id, name, password, date) VALUES (%s, %s, %s, %s)",
                                 (id, name, password, date))

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

    except mysql.connector.Error as error:
        print("数据插入失败: {}".format(error))
    cursor.close()
    conn.close()


if __name__ == '__main__':
    # 连接到SQL Server数据库
    conn_sql_server = connect_sql_server('{ODBC Driver 17 for SQL Server}', 'DESKTOP-HAI1BEH', 'T1',
                                         'sa', 'pwd_Admin')
    # 从emp表中查询10条数据
    data_sql_server = fetch_data_sql_server(conn_sql_server, 'emp', 10)
    print(data_sql_server)
    # 连接到MySQL数据库
    conn_mysql = connect_mysql('localhost', 'root', 'pwd_Admin', 'test')
    # 将数据插入到emp_copy表中
    insert_data_mysql(conn_mysql, data_sql_server, 'emp_copy')

你可能感兴趣的:(adb,android)