假定已經獲取到了某數據庫的鏈接,下面根據此鏈接獲取該數據庫的全部表名稱和及表字段信息:java
1 import io.xbs.common.utils.R; 2 import io.xbs.datasource.config.DynamicDataSource; 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.web.bind.annotation.GetMapping; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RestController; 7 8 import java.sql.Connection; 9 import java.sql.DatabaseMetaData; 10 import java.sql.ResultSet; 11 import java.sql.SQLException; 12 import java.util.ArrayList; 13 import java.util.List; 14 15 /** 16 * 獲取數據庫表結構信息 17 * 18 * @author shiyanjun 19 */ 20 @RestController 21 @RequestMapping("/app") 22 public class AppTestController { 23 24 @Autowired 25 private DynamicDataSource dataSource; 26 27 @GetMapping("dbTest") 28 public R dbTest() { 29 try { 30 Connection conn = dataSource.getConnection(); 31 32 // 獲取全部的表 33 List<String> tables = getTables(conn); 34 System.out.println("---------------獲取" + conn.getCatalog() + "庫的全部表名----------------"); 35 System.out.println(tables); 36 37 // 獲取表字段 38 for (String table : tables) { 39 List<String> columns = getColumns(conn, table); 40 System.out.println("---------------獲取" + table + "表的全部字段----------------"); 41 System.out.println(columns); 42 } 43 } catch (SQLException e) { 44 e.printStackTrace(); 45 } 46 return R.ok(); 47 } 48 49 /** 50 * 獲取數據庫中全部的表名稱 51 * 52 * @param conn 數據庫的鏈接 53 * @return 該數據庫中全部的表名稱 54 * @throws SQLException 55 */ 56 private List<String> getTables(Connection conn) throws SQLException { 57 DatabaseMetaData metaData = conn.getMetaData(); 58 ResultSet resultSet = metaData.getTables(conn.getCatalog(), "%", null, new String[]{"TABLE"}); 59 List<String> tables = new ArrayList<>(); 60 while (resultSet.next()) { 61 String tableName = resultSet.getString("TABLE_NAME"); 62 tables.add(tableName); 63 } 64 return tables; 65 } 66 67 /** 68 * 獲取指定表的全部字段名稱 69 * 70 * @param conn 數據庫鏈接 71 * @param tableName 表名稱 72 * @return 該表全部的字段名稱 73 * @throws SQLException 74 */ 75 private List<String> getColumns(Connection conn, String tableName) throws SQLException { 76 DatabaseMetaData metaData = conn.getMetaData(); 77 ResultSet rs = metaData.getColumns(conn.getCatalog(), null, tableName, null); 78 List<String> columns = new ArrayList<>(); 79 while (rs.next()) { 80 String name = rs.getString("COLUMN_NAME"); 81 columns.add(name); 82 } 83 return columns; 84 } 85 }