python连接达梦数据库方式

1、通过jaydebeapi调用jdbc

import pandas as pd  
import jaydebeapi

if __name__ == '__main__':  
    url = 'jdbc:dm://{IP}:{PORT}/{库名}'  
    username = '{username}'  
    password = '{password}'  
    jclassname = 'dm.jdbc.driver.DmDriver'  
    jarFile = '{DmJdbcDriver18.jar路径}'  
  
    conn = jaydebeapi.connect(jclassname, url, [username, password], jarFile)  
    df = pd.read_sql('select * from {表名}', conn) # 查询语句加分号结尾会有通信异常
    print(df)
title: 注意
优点:
- DmJdbcDriver18.jar比较容易找到,不需要像安装dmPython(需要安装达梦客户端)一样麻烦
- 可以与pandas配合使用,且不需要指定pandas版本

缺点:
- 不能使用pd.to_sql进行写入
- jaydebeapi.connect()直接返回了Connection,且不能配合SQLAlchemy创建engine
- 虽然不使用SQLAlchemy也可以与pandas配合使用,但是pandas会报出warning
> UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy.

2、通过官方文件安装dmPython

title: 前提
1. 需在达梦安装目录\drivers\python\dmPython执行python setup.py install
2. 将安装目录\drivers\dpi\下的所有文件复制到site-packages\dmPython下
3. 在python命令行import dmPython不报错即成功
conn = dmPython.connect(host, port, user, password, local_code=1)
with conn.cursor() as cur:
	cur.execute('{sql}')
1. 使用方法与jaydebeapi的connect类似,但是使用pd.read_sql时会报错
2. local_code=1,指定编码为UTF-8,默认为GBK

3、安装指定版本的pandas、SQLAlchemy

title: 前提
1、首先需按照[[3.1.6 连接达梦数据库#2、通过官方文件安装dmPython]],安装dmPython
2、安装sqlalchemy-dm,按理说也应该通过官方文件安装,但是直接pip install sqlalchemy-dm也能使用
3、版本要求(版本不对应会有no attribute或者no module的异常):
1. dmPython == 2.4.8
2. pandas == 1.5.3
3. SQLAlchemy == 1.3.23
4. sqlalchemy-dm == 8.1.2.98
from sqlalchemy import create_engine  
import pandas as pd

url = '{IP}:{PORT}'  
username = '{username}'  
password = '{password}'  
engine = create_engine(f'dm://{username}:{password}@{url}/', connect_args={'local_code': 1})  
df = pd.read_sql('select * from {表名};', engine)  
print(df)
``
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值