如何使用 JDBC 从数据库获取所有表名?
你可以使用 SHOW TABLES 查询获取 MySQL 中当前数据库中的表列表。
Show tables;
下面的 JDBC 程序通过执行 show tables 查询来检索数据库中的表列表。
示例
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ListingTables { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://127.0.0.1/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("Show tables"); System.out.println("Tables in the current database: "); while(rs.next()) { System.out.print(rs.getString(1)); System.out.println(); } } }
输出
Connection established...... cricketers_data customers dispatches_data employee_data myplayers sales test tutorials_data
或者,你可以使用 DatabaseMetaData 接口的 getTables() 方法。
示例
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RS_getTables { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://127.0.0.1/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Retrieving the meta data object DatabaseMetaData metaData = con.getMetaData(); String[] types = {"TABLE"}; //Retrieving the columns in the database ResultSet tables = metaData.getTables(null, null, "%", types); while (tables.next()) { System.out.println(tables.getString("TABLE_NAME")); } } }
输出
Connection established...... cricketers_data customers dispatches_data employee_data myplayers sales test tutorials_data
广告