您可以使用SHOW TABLES查询获取MySQL当前数据库中的表列表。
Show tables;
以下JDBC程序通过执行show table查询来检索数据库中的表列表。
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 { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获得连接 String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建一个Statement对象 Statement stmt = con.createStatement(); //检索数据 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 { //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获得连接 String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //检索元数据对象 DatabaseMetaData metaData = con.getMetaData(); String[] types = {"TABLE"}; //检索数据库中的列 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