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

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

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


API接口

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

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

  • db insert/realm/key/value

  • db delete/realm/key

  • db select/realm/key

  • db exists/realm/key

在拨号计划中使用:

扫描二维码关注公众号,回复: 3244899 查看本文章

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$"/>

2、通过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()

猜你喜欢

转载自blog.csdn.net/alwaysrun/article/details/81193128