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)
``

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