假定已经获取到了某数据库的连接,下面根据此连接获取该数据库的所有表名称和及表字段信息:
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 }