使用python在dolphinDB上运行SQL

发布于:2024-06-29 ⋅ 阅读:(20) ⋅ 点赞:(0)

需要先部署好dolphindb并启动数据库

步骤1:链接dolphinDB数据库

安装依赖库:pip install dolphindb

然后运行:

import dolphindb as ddb


def get_dolphin_session():
    """获取dolphinDB的session"""
    dolphin_config = {
        "host": "127.0.0.1",
        "port": 13900,
        "username": "admin",
        "password": "123456",
    }
    s = ddb.session()
    _result = s.connect(dolphin_config['host'], dolphin_config['port'], dolphin_config['username'],
                        dolphin_config['password'])
    if not _result:
        logger.error("DolphinDB 数据库无法连接!!")
        return None
    return s

步骤2. 写SQL

对于需要执行这样的一个SQL:

SELECT DISTINCT my_date FROM base_info
WHERE trade_date >= "2010-01-01"
ORDER BY trade_date DESC

使用python编写的函数如下:

def get_latest_trading_date():
    """选择my_db数据库的base_info表最新交易记录"""
    dolphin_s = get_dolphin_session()
    dolphin_dt = dolphin_s.loadTable(tableName="base_info", dbPath="dfs://my_db")
    trade_list = dolphin_dt.select("DISTINCT my_date").where(f"""
        my_date >= timestamp(2010.01.01)
        ORDER BY my_date DESC
        """).toList()
    return trade_list 

这里有几个重点:

  1. 最好提前写好SQL并且运行通过,再移植到python上,因为如果报错,dolphindb只会报错不会给错误信息
  2. 在其他数据库中,日期可以用"2010-01-01"这样表示,而在dolphindb中,会认为这是一个减法操作,需要改写为:"timestamp(2010.01.01)",这样才认为是日期(当然可以做其他转换)
  3. 最后toList()才会执行sql,也可以toDF()为dataframe格式,showSQL()直接返回执行的SQL语句而不执行
  4. 日期格式如果作为参数,传入时可以改写为如下程序:
    dt_from = pd.to_datetime("2010-01-01")
    dt_to = pd.to_datetime("2020-01-01")
    trade_list = dolphin_dt.select("DISTINCT my_date").where(f"""
            my_date >= timestamp({dt_from.strftime('%Y.%m.%d')})
            AND my_date <= timestamp({dt_to.strftime('%Y.%m.%d')})
        """).toList()
    

网站公告

今日签到

点亮在社区的每一天
去签到