查询表数据

关于数据库查询的方法,可以在查看 “编程参考”下的kScript.

get

根据主键或是ID取值

      var table = k.database.getTable("tablename");
      var item = table.get(IdOrKey);

find

查找符合条件的第一条记录

find 有两种语法格式, 根据条件或是根据字段值来查询。  

根据字段值查询接收两个参数, 一是字段名, 一是比较值。

        <script engine="kscript">

        var table = k.database.getTable("tablename"); 
        // find equal value match.
        var item = table.find("fieldname", "matchvalue"); 

        </script>

根据条件查询有以下语法格式:

字段名  比较符  比较值 

比较符有以下选项: ==,  >=,  >,  <,  <=, contains, startwith

        <script engine="kscript">

        var table = k.database.getTable("tablename");

        // Find  condition text can be one of the followings.
        // find item with field "name" value of "matchedvalue".
        var item = table.find("name=='matchedvalue'");

        // find item with field "number" bigger than or equal to 123.
        var item = table.find("number>=123");

        // find item with field "name" value contains "matchedvalue".
        var item = table.find("name contains 'matchedvalue'");

        // find item with field "name" value startwith "matchedvalue".
        var item = table.find("name startwith 'matchedvalue'");

        // && can be used to combine multiple query...
        var item = table.find("name contains na && number>=123"); 

        </script>

findAll

findAll 与find的用法一模一样, 只是它返回的是所有符合条件的记录集合,而不是单条记录。

all

返回表里面的全部记录 

var list = k.database.getTable("tablename").all();

query, orderBy, skip, take

query 可以接收跟find一样的查询条件或是不输入条件返回所有的记录集合。 

query 是链式API, 支持where, orderBy, skip 与 take。 

<script engine="kscript">
        var table = k.database.getTable("mytablename");
        var obj = {name: "myname", number: 124};
        table.add(obj);
        var obj2 = {name: "myname", number: 125};
        table.add(obj2);

        // query table
        var values = table.query("number>=123").orderBy("number").skip(1).take(10);
        // or the same
        //var values = table.query().where("number>=123").orderBy("number").skip(1).take(10); 

        </script>


        <div k-foreach="item values">
        <p k-content="item.name">name value</p>
        <p k-content="item.number">number</p>
        </div>