mysql获取表列信息、主键信息

  /**
     * 获取物理表中已存在的列信息
     * @param tbName 表名
     * @return results 查询结果
     */
    fun getExistColumnInfo(tbName:String) :List<Record> {
        var sql = "select database() AS db_name"
        var dbNameRecord = Db.findFirst(sql)
        var existColSql = """
             select COLUMN_NAME as name
             from INFORMATION_SCHEMA.COLUMNS
             where TABLE_SCHEMA=? and TABLE_NAME=?
            """
        var results = Db.find(existColSql, dbNameRecord.getStr("dbName"), tbName)
        return results
    }

  获取主键信息:

   /**
     * 获取物理表已存在的主键字段名
     * @param tbName 表名
     * @return results 查询结果
     */
    fun getExistPrimaryKeyFields(tbName: String) : List<Record>? {
        var sql = "select database() AS db_name"
        var dbNameRecord = Db.findFirst(sql)
        var existPKFiledsSql = """
                SELECT
                    k.column_name,
                    t.table_name,
                    table_schema
                FROM
                    information_schema.table_constraints t
                JOIN information_schema.key_column_usage k USING (
                    constraint_name,
                    table_schema,
                    table_name
                )
                WHERE
                    t.constraint_type = 'PRIMARY KEY'
                AND t.table_schema = ?
                AND t.table_name = ?
            """
        var results = Db.find(existPKFiledsSql, dbNameRecord.getStr("dbName"), tbName)
        return results
    }

  

原文地址:https://www.cnblogs.com/vae860514/p/9435610.html