【问题标题】:How to get a list of column names with Sqlite.swift?如何使用 Sqlite.swift 获取列名列表?
【发布时间】:2016-04-22 04:03:06
【问题描述】:

出于调试目的,我试图在我的 SQLite 表中获取列名的简单列表。我正在使用SQLite.swift framework

我的问题比How to get a list of column names on sqlite3 / iPhone? 更具体,所以我正在创建一个新问题。

使用

try db.execute("PRAGMA table_info(table_name);")

this answer 应用到documentation 对我不起作用(什么也没发生)。

【问题讨论】:

    标签: ios swift sqlite.swift


    【解决方案1】:

    假设您已经建立了一个名为db 的数据库连接,要获取列名列表,您可以使用以下代码:

    do {
    
        let tableInfo = Array(try db.prepare("PRAGMA table_info(table_name)"))
        for line in tableInfo {
            print(line[1]!, terminator: " ")
        }
        print()
    
    } catch _ { }
    

    table_name 被替换为表名的字符串。

    你也可以加

    print(tableInfo)
    

    查看有关您的表的更多 pragma 信息。

    学分

    感谢this answer 提供有关如何执行此操作的线索。

    示例函数

    来自Joe Blow 的测试例程以节省一点打字:

    func findColumns(_ tableName:String) {
    
        var asAnArray:[String] = []
        do {
            let s = try db!.prepare("PRAGMA table_info(" + tableName + ")" )
            for row in s { asAnArray.append(row[1]! as! String) }
        }
        catch { print("some woe in findColumns for \(tableName) \(error)") }
    
        let asAString = asAnArray.joined(separator: ",")
    
        print(asAnArray)
        print(asAString)
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-10
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多