【问题标题】:using an sqlite3 database with an ios8 app using Xcode 6 and swift使用带有 ios8 应用程序的 sqlite3 数据库,使用 Xcode 6 和 swift
【发布时间】:2015-04-05 06:21:51
【问题描述】:

我对编程很陌生。我正在使用 Xcode 6 并快速构建一个 iOS 8 应用程序。我的应用程序有很多数据,我使用 firefox 插件将它们组织成 sqlite3 文件。我已将这些文件放入我的项目文件夹中。他们的扩展名是 .sql 现在我需要在我的应用程序中访问该数据。我已经通过在构建阶段选项卡中添加 libsqlite3.dylib 来链接 sqlite3 库。现在我想编写代码来访问数据库。我在网上找到了很多信息,其中包含 iOS 7 及更早版本的代码和示例,使用 Objective-c,但在 iOS 8 和 swift 中却一无所获。如果有人可以帮助我或引导我朝着正确的方向前进,我将不胜感激。谢谢。

【问题讨论】:

    标签: xcode swift sqlite ios8


    【解决方案1】:

    您可以使用 sqlite.swift 框架来实现与 swift 的数据库连接 这是链接https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md

    这里是连接sqlite数据库的例子

     var db : Database!
    var cat = Expression<String>("ZCATEGORY")
    var name = Expression<String>("ZNAME")
    var user : Query!
    var stmt : Query!
    var data : Array<Row>!
    
    @IBOutlet var tabe: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
    
    
        createdb()
    }
    
    
    
     internal func createdb()
    {
      // bundle database  within your app
      let path = NSBundle.mainBundle().pathForResource("db", ofType: "sqlite")
        println(path)
        db = Database(path, readonly: true)
        // ZFOOD is table name
        user = db["ZFOOD"]
        println(db)
        // select distinct(cat) from ZFOOD
        stmt = user.select(distinct : cat)
        // Stored query result in array
         data = Array(stmt)
    
       }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        return data.count
    
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    
        let cell: AnyObject = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
         cell.textLabel.text = data[indexPath.row][cat]
        return cell as UITableViewCell
    }
    

    希望对你有帮助

    【讨论】:

    • 嗨。感谢您的回复。我真的想在不使用任何包装器的情况下自己调用 sql 库。我看过其他帖子这样做,但他们似乎都创建了表格和输入值。我已经有一个我不想修改的数据库。我只想访问表中的值。例如,该表有两列。我只想将第一列视为键,将第二列视为值。我已经很长时间没有运气了......
    • 如果您使用 sqlite.swift 包装器,那么我会帮助您,因为我从未使用过 sql 库
    • 嗨。感谢更新的代码。我使用未声明的数据库标识符,这是您的 db 变量的类型。这种类型从何而来?谢谢
    • 哦,对不起。我认为您正在使用 sqlite.swift 包装器。我希望在没有包装的情况下实现这一目标。谢谢
    • 如果您需要任何其他帮助,我会尽力帮助您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多