Java 获取Mysql数据库表的列
public class GetTableSchema { private static final String DRIVER = "com.mysql.jdbc.Driver"; private static final String URL = "jdbc:mysql://localhost:3306/loctest"; private static final String USERNAME = "root"; private static final String PASSWORD = "***"; public static void main(String[] args) throws Exception { Class.forName(DRIVER); Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); DatabaseMetaData metadata = connection.getMetaData(); ResultSet resultSet = metadata.getColumns(null, null, "loctest.user", null); while (resultSet.next()) { String name = resultSet.getString("COLUMN_NAME"); String type = resultSet.getString("TYPE_NAME"); int size = resultSet.getInt("COLUMN_SIZE"); System.out.println("Column name: [" + name + "]; type: [" + type + "]; size: [" + size + "]"); } connection.close(); } }
在项目中,需要将爬虫获取的非结构化json数据解析拉平放入关系数据库中,为了防止插入失败,需要比较表中列和插入的列,只插入数据库中有的列,没有的列邮件提醒,下次修改数据库表结构之后进行插入。
欢迎关注Java流水账公众号