FEATURED · 精选文章

Python连接达梦数据库执行SQL文件

发布时间 / 2026/8/1 10:07:08
来源 / 创域科博编辑部
栏目 / 资讯中心
Python连接达梦数据库执行SQL文件 Python 连接达梦数据库并执行 SQL 文件主要依赖dmPython官方驱动库。以下是具体步骤和代码示例。1. 环境准备安装 dmPython 驱动首先需要安装达梦官方的 Python 驱动dmPython。可通过 pip 安装或从官网下载 whl 包 。# 方法一使用 pip 安装推荐 pip install dmPython # 方法二若 pip 安装失败可从达梦官网下载对应版本的 whl 文件进行安装 # pip install dmPython-xxx.whl2. 基础连接与查询使用dmPython建立连接并执行单条 SQL 语句。import dmPython # 连接参数配置 conn_params { server: localhost, # 数据库服务器地址 port: 5236, # 端口默认 5236 user: SYSDBA, # 用户名 password: SYSDBA, # 密码 autoCommit: True # 是否自动提交事务 } try: # 建立数据库连接 conn dmPython.connect(**conn_params) print(达梦数据库连接成功) # 创建游标 cursor conn.cursor() # 执行单条 SQL 查询 cursor.execute(SELECT Hello, DM! AS greeting FROM dual) result cursor.fetchone() print(f查询结果: {result[0]}) # 执行单条 DML 语句如 INSERT cursor.execute(INSERT INTO test_table (id, name) VALUES (1, Python)) print(插入数据成功) # 关闭游标和连接 cursor.close() conn.close() except dmPython.Error as e: print(f达梦数据库错误: {e}) except Exception as e: print(f其他错误: {e})3. 执行 SQL 文件要执行整个 SQL 文件需要读取文件内容并按分号 (;) 或其他定界符分割成独立的 SQL 语句依次执行。注意处理可能存在的注释和空行。import dmPython import re def execute_sql_file(host, port, user, password, database, sql_file_path): 执行 SQL 文件 :param sql_file_path: SQL 文件路径 conn None cursor None try: # 1. 建立连接 conn dmPython.connect(serverhost, portport, useruser, passwordpassword, autoCommitFalse) cursor conn.cursor() print(数据库连接成功开始执行 SQL 文件...) # 2. 读取 SQL 文件内容 with open(sql_file_path, r, encodingutf-8) as f: sql_content f.read() # 3. 预处理移除多行注释/* ... */和单行注释-- # 移除 /* */ 注释 sql_content re.sub(r/\*.*?\*/, , sql_content, flagsre.DOTALL) # 移除 -- 注释 sql_content re.sub(r--.*$, , sql_content, flagsre.MULTILINE) # 4. 按分号分割 SQL 语句确保分号不在引号内 # 这是一个简单的分割复杂 SQL 可能需要更严谨的解析器 sql_statements [] current_statement [] in_string False string_char None for char in sql_content: if char in (, ) and not (len(current_statement) 0 and current_statement[-1] \\): if not in_string: in_string True string_char char elif string_char char: in_string False string_char None if not in_string and char ;: stmt .join(current_statement).strip() if stmt: # 忽略空语句 sql_statements.append(stmt) current_statement [] else: current_statement.append(char) # 处理最后一条没有分号的语句 final_stmt .join(current_statement).strip() if final_stmt: sql_statements.append(final_stmt) # 5. 逐条执行 SQL 语句 success_count 0 for idx, sql in enumerate(sql_statements, 1): sql sql.strip() if not sql: continue try: cursor.execute(sql) print(f 语句 {idx} 执行成功: {sql[:50]}...) # 打印前50个字符 success_count 1 except dmPython.Error as e: print(f 语句 {idx} 执行失败: {e}) print(f 失败语句: {sql}) conn.rollback() # 出错时回滚当前事务 raise e # 可选择抛出异常或继续执行 # 6. 提交事务 conn.commit() print(fSQL 文件执行完成。成功 {success_count} 条共 {len(sql_statements)} 条语句。) except FileNotFoundError: print(f错误未找到 SQL 文件 {sql_file_path}) except dmPython.Error as e: print(f达梦数据库错误: {e}) if conn: conn.rollback() except Exception as e: print(f其他错误: {e}) if conn: conn.rollback() finally: # 7. 关闭连接 if cursor: cursor.close() if conn: conn.close() # 使用示例 if __name__ __main__: # 替换为你的实际连接信息和 SQL 文件路径 execute_sql_file( hostlocalhost, port5236, userSYSDBA, passwordSYSDBA, sql_file_path./your_script.sql # SQL 文件路径 )4. 使用连接池推荐用于生产环境对于频繁操作建议使用连接池如DBUtils或SQLAlchemy来管理连接 。使用 DBUtils创建连接池from dbutils.pooled_db import PooledDB import dmPython # 创建达梦数据库连接池 pool PooledDB( creatordmPython, # 指定使用 dmPython 驱动 maxconnections10, # 池中最大连接数 mincached2, # 初始化时创建的空闲连接数 maxcached5, # 池中空闲连接的最大数 blockingTrue, # 连接池满时是否阻塞等待 hostlocalhost, port5236, userSYSDBA, passwordSYSDBA, autoCommitTrue ) # 从连接池获取连接并执行 SQL 文件简化版 def execute_sql_file_with_pool(pool, sql_file_path): conn pool.connection() # 从池中获取连接 cursor conn.cursor() try: with open(sql_file_path, r, encodingutf-8) as f: # 简单按分号分割执行生产环境建议使用上述更健壮的分割逻辑 sql_commands f.read().split(;) for cmd in sql_commands: cmd cmd.strip() if cmd: cursor.execute(cmd) print(SQL 文件执行成功使用连接池。) except Exception as e: print(f执行失败: {e}) finally: cursor.close() conn.close() # 将连接归还给池而非真正关闭 # 使用示例 execute_sql_file_with_pool(pool, ./your_script.sql)5. 关键参数与常见问题参数/问题说明与解决方案连接参数dmPython.connect()关键参数server(主机),port(端口),user(用户),password(密码),autoCommit(自动提交) 。驱动未安装错误提示ModuleNotFoundError: No module named dmPython需通过pip install dmPython安装 。连接失败检查数据库服务是否启动、防火墙是否开放端口默认5236、用户名密码是否正确 。SQL 文件编码确保 SQL 文件编码如 UTF-8与读取编码一致否则会出现乱码或解析错误。事务管理默认autoCommitFalse需手动conn.commit()提交或conn.rollback()回滚 。批量执行文件时建议显式管理事务。性能优化对于大批量数据操作可在连接参数中设置batchTrue或使用cursor.executemany()。参考来源连接达梦数据库的N种方式达梦数据库python 操作手册Python连接达梦数据库并实现简单查询的完整指南使用Python及PHP连接达梦数据库python 连接达梦数据库
RELATED — 相关阅读

相关资讯

LATEST — 最新资讯

最新发布

TODAY — 本日精选

新闻

WEEKLY — 本周精选

新闻

MONTHLY — 本月精选

新闻