python3导入sql文件

导入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)

你可能感兴趣的:(sql,数据库)