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

前提条件

  • 已获取云原生多模数据库Lindorm宽表引擎的连接地址,具体操作请参见访问实例
  • 已安装Python环境,且Python版本为3.7及以上版本。

使用限制

本文操作仅适用于Lindorm宽表模式,不支持Lindorm宽表Serverless模式。

操作步骤

  1. 执行pip install phoenixdb命令安装phoenixdb,以1.2.0版本为例。
    pip install phoenixdb==1.2.0
  2. 指定连接数据库的名称、用户名以及密码,初始化连接参数。
    connect_kw_args = {'lindorm_user': 'Lindorm控制台获取的数据库用户名', 'lindorm_password': 'Lindorm控制台获取的数据库密码', 'database': '业务指定的数据库名称'}

    参数说明

    参数 示例 说明
    lindorm_user root 用户名、密码。您可以通过云原生多模数据库Lindorm集群管理系统查看用户名和密码,如果您忘记密码,可以通过Lindorm宽表引擎的集群管理系统修改密码,具体操作请参见管理用户
    lindorm_password root
    database default 数据库名称。您可以连接任意有权限且已存在的数据库,如果没有指定连接的数据库,则默认连接default数据库。
  3. 指定数据库连接地址database_url和连接的初始化参数connect_kw_args,创建数据库连接。
    connection = phoenixdb.connect(database_url, autocommit=True, **connect_kw_args)

    参数说明

    参数 说明
    database_url Lindorm宽表SQL地址,例如:http://ld-bp10m54739kg9****-proxy-lindorm.lindorm.rds.aliyuncs.com:30060。获取连接地址的具体操作,请参见查看连接地址
    autocommit 自动提交,取值必须为true。
    connect_kw_args 初始化连接参数,您无需修改。
  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)
    
        # 禁用表,删除表之前需要先禁用表
        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语法手册