检索表名列表

huangapple go评论85阅读模式
英文:

Retrieve list of table names

问题

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

关于tableList命令的文档称此方法返回一个字符串列表,但事实并非如此。它实际上返回一个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。

英文:

I want to get the list of tables in a database.

The documentation of the tableList command says this method returns a list of strings, but that is not exactly the case. It actually returns a TableList object.

And when I run..

r.db(&quot;test&quot;).tableList().run(conn);

I get a Result&lt;Object&gt; object as result with one entry that is really an ArrayList with all table names I want.

So, is this actually how this is supposed to work now:

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&lt;?&gt; tableList = new ArrayList&lt;&gt;((Collection&lt;?&gt;) tableListObject);

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

Seems rather complicated to me, is there an official/better way to do this?

I am using the RethinkDB Java driver version 2.4.4.

答案1

得分: 1

你可以利用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<?>

英文:

You can take advantage of the run() method which allows you to specify the class of the returned results - in this case an array of strings:

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

For me, this prints the following in my test DB:

movies
tv_shows

Updated to use List&lt;?&gt; as suggested by @Johannes.

huangapple
  • 本文由 发表于 2020年9月6日 04:29:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63758220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定