首页 > 解决方案 > 如何在 Swift 中检测 SQLite 数据库中的列类型?

问题描述

我想在 Swift-5 中获取 SQLite 数据库中特定表的列类型。

我尝试使用以下代码,但表中没有数据,它不起作用。

// 1=Int, 2=Decimal, 3=String
static func getColumnType(database: FMDatabase,tableName:String, colName:String)->Int{
    
    var type = 0
    if database.open()
    {
        let queryCount = "SELECT * FROM \(tableName)"
        
        if let rs = database.executeQuery(queryCount, withArgumentsIn: []) {
            do {
                while(rs.next()) {
                    let countColumn:Int = Int(rs.columnCount)
                     
                    for index in 0 ..< countColumn {
                        let columnName:String = rs.columnName(for: Int32(index))!
                        if(columnName != colName) {
                             continue
                        }

                        if let index = DBConst.elements.firstIndex(of: columnName) {
                            print("find int :: \(index) name :: \(columnName)")
                            type = 1
                            break
                        }else if let index = DBConst.elementsDecimal.firstIndex(of: columnName) {
                            print("find Decimal :: \(index) name :: \(columnName)")
                            type = 2
                            break
                        }else{
                            print("find not string :: \(index) name :: \(columnName)")
                            type = 3
                            break
                        }
                    }
                }
            }catch {
                print("error")
            }
            
        }
    }
    
    return type
}

标签: iosswiftsqlite

解决方案


推荐阅读