FreeSWITCH中数据库API与Lua操作简介

目录

API接口

db操作命令

group操作命令

lua中主要接口说明

lua中插入数据

lua中查询数据库


mod_db实现了数据库(sqlit或ODBC)操作的api与app(可在拨号计划中使用)。

在lua脚本中,通过freeswitch.Dbh可方便地对数据库进行操作,后面以默认的Sqlite数据库为例进行说明。

 

API接口

通过API接口的数据会被存到call_limit.db数据库中。

db操作命令

通过db(与hash命令类似)操作,插入一个值到数据库(db_data表)中,realm与key字段作为二元组,唯一决定值

  • db insert/realm/key/value

  • db delete/realm/key

  • db select/realm/key

  • db exists/realm/key

在拨号计划中使用:

Delete an entry from the database:

<action application="db" data="delete/realm/key"/>

Retrieve a value from the database:

<action application="set" data="var=${db(select/realm/key)}"/>

Use as a condition:

<condition field="${db(select/realm/key)}" expression="^value$"/>

Use as a condition checking if item exists:

<condition field="${db(exists/realm/key)}" expression="^true$"/>

 

group操作命令

通过group命令,插入一组端口(endpoint)数据库中(group_data表)中,允许同一个grpname对应多个值

  • group insert:grpname:sipurl

  • group delete:grpname:sipurl

  • group call:grpname[:order]

在拨号计划中使用

Insert a group entry:

<action application="group" data="insert:groupname:sipurl"/> 

Delete a group entry:

<action application="group" data="delete:groupname:sipurl"/>

Select a group entry:

<action application="set" data="api_result=${group(call:groupname)}"/>

 

lua中主要接口说明

通过以下接口可方便地进行数据库的增删查功能:

  • freeswitch.Dbh("sqlite://my_db") :使用连接池中的连接,连接到数据库‘my_db‘(存放在db目下的my_db.db,若不存在则创建);若是其他数据库使用freeswitch.Dbh(odbc://my_db:uname:passwd)。

  • dbh:connected():检测是否已连接;

  • dbh:test_reactive("test_sql", "drop_sql", "reactive_sql"):执行test_sql,若失败则执行drop_sql和reactive_sql (一般用于数据库初始化);

  • dbh:query("query", function()) :执行query语句,并循环对每一条返回执行后面的回调函数(如果你返回一个非零的数字,则会中断循环)。

  • dbh:affected_rows() :返回最近执行的 INSERT, DELETE or UPDATE 所影响的行数。

  • dbh:release():释放连接。

 

lua中插入数据

local dbh=freeswitch.Dbh("sqlite://my_db")

assert(dbh:connected())

dbh:test_reactive("Select * from myTable",

    "Drop Table myTable" --获取数据失败,则删除表

    "Create Table MyTable(Id int Primary Key Not NULL, Info Varchar(100) Not NULL)") -- 重新创建表

dbh:query("Insert or Replace into MyTable(1, "test")) --若存在则更新,否则插入

print(dbh:affected_rows())

dbh:release()

 

lua中查询数据库

local dbh=freeswitch.Dbh("sqlite://my_db")

assert(dbh:connected())

dbh:query("Select Id, Info From MyTable Where Id<10",

    function(row) -- 对每一列进行操作

        print(row.Id, row.Info)

        if( row.Id == 5 ) then 

            dbh:query("Update MyTable Set Info='it is five' Where Id=" .. row.Id)

        end

    end)

dbh:release()

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值