用途:用于获取指定数据库中表以及栏目的各项信息(包括字段名、注释、类型、是否为空等)
该类用于存储数据库信息(用户名、密码等)
该类用于存储栏目的各项信息,按需拓展。
- 获取数据库连接
public static Connection getConnection(CfsDatabase cfsDatabase) { Connection conn = null; try { conn = DriverManager.getConnection(cfsDatabase.getUrl(), cfsDatabase.getUserName(), cfsDatabase.getPassword()); } catch (SQLException e) { LOGGER.error("获取数据库连接失败", e); } return conn; }
-
获取数据库下所有表名
public static List<String> getTableNames(CfsDatabase cfsDatabase) { List<String> tableNames = new ArrayList<>(); Connection conn = getConnection(cfsDatabase); ResultSet rs = null; try { //获取数据库的元数据 DatabaseMetaData db = conn.getMetaData(); //从元数据中获取到所有的表名 rs = db.getTables("lwj_odin_v2", null, null, new String[]{"TABLE"}); while (rs.next()) { tableNames.add(rs.getString(3)); } } catch (SQLException e) { LOGGER.error("获取数据库表信息失败", e); } finally { try { rs.close(); closeConnection(conn); } catch (SQLException e) { LOGGER.error("关闭数据库连接失败", e); } } return tableNames; }
-
获取表中字段和注释的关系并存入map对象
public static Map<String,String> getColumnComments(String tableName, CfsDatabase cfsDatabase) { //用于存储字段与注释 Map<String,String>columnMap=new HashMap<>(); //与数据库的连接 Connection conn = getConnection(cfsDatabase); PreparedStatement pStemt = null; String tableSql = SQL + tableName; ResultSet rs = null; try { ps = conn.prepareStatement(tableSql); rs = ps.executeQuery("show full columns from " + tableName); while (rs.next()) { columnMap.put(rs.getString("Field"),rs.getString("Comment")); } } catch (SQLException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); closeConnection(conn); } catch (SQLException e) { LOGGER.error("数据库操作失败", e); } } } return columnMap; }
-
获取表中所有字段信息
public static List<DatabaseInfo> getColumnNames(String tableName,CfsDatabase cfsDatabase) { //获取字段和注释的关联关系 Map<String,String> columnMap=DatabaseUtil.getColumnComments(tableName,cfsDatabase); List<DatabaseInfo> databaseInfos = new ArrayList<>(); //与数据库的连接 Connection conn = getConnection(cfsDatabase); PreparedStatement pStemt = null; String tableSql = SQL + tableName; try { ps= conn.prepareStatement(tableSql); //结果集元数据 ResultSetMetaData rsmd = ps.getMetaData(); //表列数 int size = rsmd.getColumnCount(); for (int i = 1; i <= size; i++) { DatabaseInfo databaseInfo=new DatabaseInfo(); //获取字段名称 databaseInfo.setFieldName(rsmd.getColumnName(i)); //获取字段类型 databaseInfo.setType(rsmd.getColumnTypeName(i)); //字段是否为空 databaseInfo.setEmptyStatus(String.valueOf(rsmd.isNullable(i))); //字段注释 databaseInfo.setAnnotation(columnMap.get(rsmd.getColumnName(i))); databaseInfos.add(databaseInfo); } } catch (SQLException e) { LOGGER.error("获取数据库表的列信息失败", e); } finally { if (pStemt != null) { try { pStemt.close(); closeConnection(conn); } catch (SQLException e) { LOGGER.error("关闭数据库连接失败", e); } } } return databaseInfos; }