我想从特定数据库中检索所有表名。我尝试了以下代码
try {
DatabaseMetaData dbmd = connection.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbmd.getTables(null, null, "%", types);
while (rs.next()) {
System.out.println(rs.getString("TABLE_NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
但是它给出了nullpointer异常。
答案 0 :(得分:1)
以下示例显示方法conn.getMetaData()
将返回预期数据。
public class Main {
public static void main(String[] args) throws SQLException {
try (Connection conn = DriverManager.getConnection("jdbc:sqlite:testdata.db");
Statement stmt = conn.createStatement()) {
String sql = "CREATE TABLE IF NOT EXISTS TEST_TABLE"
+ " (ID INT PRIMARY KEY NOT NULL,"
+ " NAME TEXT NOT NULL, "
+ " ADDRESS CHAR(50))";
stmt.executeUpdate(sql);
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.printf("table name: %s%n", rs.getString("TABLE_NAME"));
}
}
}
}
产生输出:
table name: TEST_TABLE
答案 1 :(得分:0)
尝试以下方法:
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
System.out.println(rs.getString(3));
}