如何从数据库中获取所有表名?
我想从数据库模式中检索所有表名称,并且如果可能的话,获取以指定前缀开头的所有表。
我尝试使用 JDBC 的 connection.getMetaData().getTables()
但它根本不起作用。
Connection jdbcConnection = DriverManager.getConnection("", "", "");
DatabaseMetaData m = jdbcConnection.getMetaData();
ResultSet tables = m.getTables(jdbcConnection.getCatalog(), null, "TAB_%", null);
for (int i = 0; i < tables.getMetaData().getColumnCount(); i++) {
System.out.println("table = " + tables.getMetaData().getTableName(i));
}
有人可以帮我解决这个问题吗?
I'd like to retrieve all table names from a database schema, and, if possible, get all table starting with a specified prefix.
I tried using JDBC's connection.getMetaData().getTables()
but it didn't work at all.
Connection jdbcConnection = DriverManager.getConnection("", "", "");
DatabaseMetaData m = jdbcConnection.getMetaData();
ResultSet tables = m.getTables(jdbcConnection.getCatalog(), null, "TAB_%", null);
for (int i = 0; i < tables.getMetaData().getColumnCount(); i++) {
System.out.println("table = " + tables.getMetaData().getTableName(i));
}
Could someone help me on this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您需要调用
next()
迭代 ResultSet。这是来自 java2s.com 的示例:
列 3 是
TABLE_NAME
(请参阅DatabaseMetaData::getTables
)。You need to iterate over your ResultSet calling
next()
.This is an example from java2s.com:
Column 3 is the
TABLE_NAME
(see documentation ofDatabaseMetaData::getTables
).在您的示例中,问题是在 DatabaseMetaData 的 getTables 函数中传递表名称模式。
有些数据库支持大写标识符,有些数据库支持小写标识符。例如,oracle 以大写形式获取表名,而 postgreSQL 以小写形式获取表名。
DatabaseMetaDeta提供了确定数据库如何存储标识符的方法,可以大小写混合,大写,小写见:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()
从下面的示例中,您可以获得提供表名称模式的所有表和视图,如果您只想要表,则从 TYPES 数组中删除“VIEW”。
In your example problem is passed table name pattern in getTables function of DatabaseMetaData.
Some database supports Uppercase identifier, some support lower case identifiers. For example oracle fetches the table name in upper case, while postgreSQL fetch it in lower case.
DatabaseMetaDeta provides a method to determine how the database stores identifiers, can be mixed case, uppercase, lowercase see:http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#storesMixedCaseIdentifiers()
From below example, you can get all tables and view of providing table name pattern, if you want only tables then remove "VIEW" from TYPES array.
如果您想使用高级 API,它隐藏了数据库模式元数据的大量 JDBC 复杂性,请查看这篇文章:http://www.devx.com/Java/Article/32443/1954
If you want to use a high-level API, that hides a lot of the JDBC complexity around database schema metadata, take a look at this article: http://www.devx.com/Java/Article/32443/1954
在较新版本的 MySQL 连接器中,如果未传递目录,还会列出默认表
In newer versions of MySQL connectors the default tables are also listed if catalog is not passed