从 Session 迁移到 DBConnection
Session 继承自
DBConnection,并保留了向后兼容的构造和方法参数。主要差异是:Session
可以在构造时传入 host、port、userid、password
并立即连接;DBConnection 需要先创建实例,再调用 connect() 建立连接。
Session.connect()、Session.run() 和
Session.login() 会把旧参数名转换为 DBConnection
使用的新参数名后再执行;Session.upload()
则沿用父类实现。两者共享超时、重连和高可用机制,Session 额外提供数据库对象操作、流订阅等封装。
迁移时建议按以下顺序处理:
-
将
Session构造函数中的连接参数移到connect()。 -
将
run()迁移为exec(),并把参数名改为DBConnection的蛇形命名。 -
如果代码依赖
table、loadTable、database、subscribe等Session专有方法,继续使用Session;这些 API 不能仅通过参数改名迁移到DBConnection。
注意:Session 的兼容接口仍使用旧参数名;在 DBConnection 中传入
clearMemory、pickleTableToList 等旧参数名会报错。
| 迁移项 | Session 参数 |
DBConnection 参数 |
|---|---|---|
| SSL | enableSSL | enable_ssl |
| 异步模式 | enableASYNC | enable_async |
| 序列化协议 | enablePickle=True / False |
protocol="pickle" / "ddb" |
| Python 解析器 | python=True |
parser="python" |
| SQL 标准兼容 | sqlStd | sql_std |
| 高可用 | highAvailability | enable_high_availability |
| 高可用站点 | highAvailabilitySites | high_availability_sites |
| 心跳间隔 | keepAliveTime | keep_alive_time |
| 重连次数 | tryReconnectNums | try_reconnect_nums |
| 公开名称 | usePublicName | use_public_name |
| 读写超时 | readTimeout / writeTimeout | timeout /
net_timeout(datetime.timedelta);兼容参数
read_timeout / write_timeout 使用秒数 |
| 网络超时 | netTimeout | net_timeout |
| 连接超时 | timeout | timeout(datetime.timedelta) |
| 登录加密参数 | enableEncryption(login()) |
enable_encryption |
| 执行后清理内存 | clearMemory | clear_memory |
| 表转列表 | pickleTableToList | table_to_list |
| 拉取批大小 | fetchSize | fetch_size |
| 禁用 Decimal | disableDecimal | disable_decimal |
import dolphindb as ddb
# Session:旧写法,参数使用驼峰命名
s = ddb.Session()
try:
if not s.connect("localhost", 8848, "admin", "your_password"):
raise RuntimeError("Failed to connect to DolphinDB")
s.run("table(1..3 as a)", clearMemory=True, pickleTableToList=True)
finally:
s.close()
# DBConnection:迁移后,使用 exec() 和蛇形参数名
conn = ddb.DBConnection()
try:
if not conn.connect("localhost", 8848, "admin", "your_password"):
raise RuntimeError("Failed to connect to DolphinDB")
conn.exec("table(1..3 as a)", clear_memory=True, table_to_list=True)
finally:
conn.close()
注意:
-
默认协议是 DDB;只有迁移显式设置
enablePickle=True的代码时,才需要指定protocol="pickle"。 -
PICKLE 已弃用,Python 3.13 及以上会自动改用 DDB。
-
enableChunkGranularityConfig 仅用于
Session.database(),应继续保留在Session上;DBConnection没有对应参数。 -
enableEncryption 和 enable_encryption 目前都未实现凭据加密,改名不会改变该行为。
