jdbc获取数据库所有表名以及表字段

fun connectDb() {
    Class.forName("com.mysql.jdbc.Driver")
    val url = "jdbc:mysql://xxx:3306/xxx?user=xxx&password=xxx"
    val conn = DriverManager.getConnection(url)

    val md = conn.metaData
    val rs = md.getTables(null, null, "%", null)
    while (rs.next()) {
        //表名
        val tableName = rs.getString(3)
        println("开始扫描表 '$tableName'")
        val statement = conn.createStatement()
        val results = statement.executeQuery("SELECT * FROM $tableName limit 0")
        val metadata = results.metaData
        val columnCount = metadata.columnCount
        for (i in 1..columnCount) {
            val columnName = metadata.getColumnName(i);
            print(columnName)
            print(", ")
        }
        println()
    }
    conn.close()
}

fun main(args: Array) {
    connectDb()
}

 

你可能感兴趣的:(数据库)