如何使用Sqlite.swift获取列名列表? [英] How to get a list of column names with Sqlite.swift?

查看:202
本文介绍了如何使用Sqlite.swift获取列名列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For debugging purposes I am trying to get a simple list of the column names in my SQLite table. I am using the SQLite.swift framework.

我的问题比更具体在sqlite3/iPhone上获取列名列表?所以我要创建一个新问题.

My question is more specific than How to get a list of column names on sqlite3 / iPhone? so I am creating a new question.

使用

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

通过将此答案应用于

by applying this answer to the documentation didn't work for me (nothing happened).

推荐答案

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

Assuming you already have a database connection called db set up, to get a list of the column names, you can use the following code:

do {

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

} catch _ { }

其中table_name被替换为表格名称的文字字符串.

where table_name is replaced with the literal string of your table's name.

您还可以添加

print(tableInfo)

查看有关表的更多实用信息.

to see more pragma info about your table.

积分

感谢此答案,以获取有关执行此操作的线索.

Thanks to this answer for clues of how to do this.

示例功能

Joe Blow 中经过测试的例程,以保存一些键入内容:

Tested routine from Joe Blow to save a little typing:

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)
}

这篇关于如何使用Sqlite.swift获取列名列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆