文档

基于Python DB-API的应用开发

更新时间:

本文介绍通过Python DB-API开发Lindorm宽表应用的方法和示例。

前提条件

  • 已安装Python环境,且Python版本为3.7及以上版本。

  • 已将客户端的IP地址添加至Lindorm白名单。如何添加,请参见设置白名单

使用限制

LindormServerless不支持通过Python DB-API访问Lindorm宽表引擎。

操作步骤

  1. 执行pip install phoenixdb命令安装phoenixdb,以1.2.0版本为例。

    pip install phoenixdb==1.2.0
  2. 指定连接数据库的名称、用户名以及密码,初始化连接参数。

    connect_kw_args = {'lindorm_user': '<userName>', 'lindorm_password': '<userPassword>', 'database': '<database>'}

    参数说明

    参数

    说明

    lindorm_user

    Lindorm的用户名、密码。

    如果忘记密码,可以通过Lindorm宽表引擎的集群管理系统修改密码,具体操作请参见管理用户

    lindorm_password

    database

    数据库名称。您可以指定任意有权限的数据库。

    如果没有指定数据库,则默认连接default数据库。

  3. 指定数据库连接地址database_url和连接的初始化参数connect_kw_args,创建数据库连接。

    database_url = '<lindorm_sql_url>'
    connection = phoenixdb.connect(database_url, autocommit=True, **connect_kw_args)

    参数说明

    参数

    说明

    database_url

    Lindorm宽表SQL地址。获取连接地址,请参见查看连接地址

    如果客户端部署在与Lindorm相同VPC的ECS上,可以使用专有网络地址,否则请先开通公网地址,并使用公网地址。

    配置时,请删除连接地址http之前的字符串。

    示例:database_url = 'http://ld-bp10m54739kg9****-proxy-lindorm.lindorm.rds.aliyuncs.com:30060'

    autocommit

    自动提交,取值必须为true。

    **connect_kw_args

    将步骤2connect_kw_args中的所有关键字参数传递给phoenixdb.connect()方法,用于建立数据库连接。

  4. 建立连接后,执行DDL操作和DML操作,示例代码如下。

    with connection.cursor() as statement:
        # 创建表
        sql_create_table = "create table if not exists test_python(c1 integer, c2 integer, primary key(c1))"
        print(sql_create_table)
        statement.execute(sql_create_table)
    
        # 插入一行数据
        sql_upsert = "upsert into test_python(c1, c2) values(1,1)"
        print(sql_upsert)
        statement.execute(sql_upsert)
    
        # 插入多行数据
        with connection.cursor() as stat:
            sql_upsert = "upsert into test_python(c1, c2) values(?,?)"
            print(sql_upsert)
            stat.executemany(sql_upsert, [(2, 2), (3, 3)])
    
        # 删除数据
        sql_delete = "delete from test_python where c1=2"
        print(sql_delete)
        statement.execute(sql_delete)
    
        # 修改数据
        sql_update = "upsert into test_python(c1, c2) values(1,10)"
        print(sql_update)
        statement.execute(sql_update)
    
        # 查询
        sql_select = "select * from test_python"
        print(sql_select)
        statement.execute(sql_select)
        rows = statement.fetchall()
        print(rows)
    
        # 禁用表。宽表引擎版本为2.2.16至2.4.1时,删除表前需先禁用表
        sql_offline_table = "offline table test_python"
        print(sql_offline_table)
        statement.execute(sql_offline_table)
    
        # 删除表
        sql_drop_table = "drop table if exists test_python"
        print(sql_drop_table)
        statement.execute(sql_drop_table)
    
    # 关闭连接
    connection.close()
    说明

    完整的示例代码请参见Python使用示例

语法参考

关于Lindorm宽表SQL的语法使用请参见Lindorm宽表SQL语法手册

  • 本页导读 (1)
文档反馈