从RethinkDB获取数据

时间:2018-05-15 22:22:30

标签: model dart rethinkdb

在“Dart可伸缩应用程序开发”一书中,有一个使用RethinkDB的例子

  class UserStore{
      final List<User> users = new List();
      User user;
      Rethinkdb rdb = new Rethinkdb();
      Connection conn;

  // opening a connection to the database:
  openAndStore() {
    rdb.connect(db: "test", port:9090, host: "127.0.0.1").
    then((_conn) {
      conn = _conn;
      storeData(conn);
    }).catchError(print);
  }



  storeData(conn) {
    List jobsMap = new List();
    for (user in users) {
      var jobMap = user.toMap();
      jobsMap.add(jobMap);
    }
// storing data:
    rdb.table("users").insert(jobsMap).run(conn)
        .then((response)=>print('documents inserted'))
        .catchError(print);
// close the database connection:
    close();
  }


  openAndRead() {
    rdb.connect(db: "test", port:9090, host: "127.0.0.1").then((_conn) {
      conn = _conn;
      readData(conn);
    }).catchError(print);
  }
// reading documents:
  readData(conn) {
    print("test3");
    rdb.table("users").getAll("1,2,3").run(conn).then((results) {
      processJob(results);
      close();
    });
  }


// working with document data:

  processJob(results) {
    for (var row in results) {
// Refer to columns by nam:
      print('${row.id}');
      }
      }
  close() {
    conn.close();
  }

但在实践中,该程序不会导致死亡。虽然它被称为openAndRead()。

catchError不起作用。  使用模型和RethinkDB的最简单方法是什么?

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解这个问题,但我建议使用Dart的async/await语法,因为这样可以让代码更容易阅读。

例如

main() async {
  Rethinkdb rdb = new Rethinkdb();
  try {
    // get the connection
    Connection conn = await rdb.connect(port: 28015);

    // insert a row into the users table
    await rdb.table('users').insert({'a': 'b'}).run(conn);

    // query the users table
    Cursor c = await rdb.table('users').run(conn);

    // grab all the data from the cursor
    List rows = await c.toList();

    print(rows);

    // close the connection
    conn.close();
  } catch (e) {
    print('catching exception $e');
  }
}

您可以创建一个类来保存数据库连接,这样您就不需要继续打开和关闭它了。

class Database {
  Rethinkdb _rdb = new Rethinkdb();
  Connection _conn;

  connect(int port) async {
    _conn = await _rdb.connect(port: port);
  }

  Future<List> fetch() async {
    Cursor c = await _rdb.table('users').run(_conn);
    return await c.toList();
  }

  close() {
    _conn.close();
  }
}

另外,驾驶员的错误处理可能会被打破。 驱动程序抛出一个错误,当它可能正在完成带有错误的Future时,在这里:

}).catchError((err) => throw new RqlDriverError(
    "Could not connect to $_host:$_port.  Error $err"));
return _completer.future;

对于软件包开发人员来说,这可能值得一提。你会注意到在我上面的main()中,没有捕获异常。