检索表名称列表

问题描述

我想获取数据库中的表列表。

The documentation of the tableList command说此方法返回一个字符串列表,但实际情况并非如此。实际上,它返回一个TableList对象。

当我跑步时..

r.db("test").tableList().run(conn);

作为结果,我得到一个Result<Object>对象,它实际上是一个ArrayList,带有我想要的所有表名。

那么,这实际上是现在应该如何工作的?

Connection connection = r.connection().hostname(DEFAULT_HOSTNAME).port(DEFAULT_PORT).connect();

Object tableListObject = r.db(DEFAULT_DB_NAME).tableList().run(connection).single();

if (tableListObject instanceof Collection) {
    List<?> tableList = new ArrayList<>((Collection<?>) tableListObject);

    for(Object tableName : tableList) {
        System.out.println(tableName);
    }
}

对我来说似乎很复杂,是否有官方/更好的方法来做到这一点?

我正在使用RethinkDB Java驱动程序版本2.4.4。

解决方法

您可以利用run()方法,该方法允许您指定返回结果的类-在这种情况下为字符串数组:

Connection conn = r.connection().hostname("localhost").port(32769).connect();
List<?> tables = r.db("test").tableList().run(conn,ArrayList.class).first();
if (tables != null) {
    tables.forEach(System.out::println);
}

对我来说,这会在我的测试数据库中打印以下内容:

movies
tv_shows

已按照@Johannes的建议更新为使用List<?>