python3导入sql文件

发布时间:2024年01月16日

导入1

import logging
import pymysql

# 定义连接参数
db_config = {
    "host": "192.168.0.52",
    "user": "root",
    "password": "S3spxRSi2P",
    "port": 8541,
    "database": "sport01"
}

# 配置日志记录
logger = logging.getLogger()
logger.setLevel(logging.INFO)  # 设置日志级别为 INFO
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(handler)

try:
    # 连接数据库
    with pymysql.connect(**db_config) as conn:
        with conn.cursor() as cursor:
            with open("test.sql", "r", encoding="utf-8") as f:
                sql_content = f.read()
                cursor.execute(sql_content)
                logger.info("SQL 语句执行成功")

            conn.commit()  # 提交事务
except pymysql.Error as e:
    logger.error("SQL 执行错误: %s", e)

导入2 先导入DDL再导入DML

import logging
import pymysql

# 定义连接参数
db_config = {
    "host": "192.168.0.52",
    "user": "root",
    "password": "S3spxRSi2P",
    "port": 8541,
    "database": "sport01"
}

# 配置日志记录
logger = logging.getLogger()
logger.setLevel(logging.INFO)  # 设置日志级别为 INFO
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
logger.addHandler(handler)

try:
    # 连接数据库
    with pymysql.connect(**db_config) as conn:
        with conn.cursor() as cursor:
            # 设置编码
            cursor.execute("SET NAMES utf8mb4")

            # 执行 DDL 语句
            cursor.execute(open("DDL.sql", "r", encoding="utf-8").read())
            logger.info("执行 DDL 语句成功")

            # 执行 DML 语句
            cursor.execute(open("DML.sql", "r", encoding="utf-8").read())
            logger.info("执行 DML 语句成功")

            conn.commit()  # 提交事务
except pymysql.Error as e:
    logger.error("SQL 执行错误: %s", e)
文章来源:https://blog.csdn.net/weixin_42562106/article/details/135627442
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。