我对编程很新。我正在使用Xcode 6和swift来构建iOS 8应用程序。我的应用程序有很多数据,我已经使用firefox添加组织成sqlite3文件。我已将这些文件放入我的项目文件夹中。他们的扩展名是.sql现在我需要在我的应用程序中访问该数据。我已经通过在构建阶段选项卡中添加libsqlite3.dylib来链接sqlite3库。现在我想写代码来访问数据库。我已经在iOS 7及更早版本的代码和示例中使用objective-c在线发现了很多信息,但iOS 8和swift都没有。如果有人可以帮助我或带领我朝着正确的方向前进,我将不胜感激。感谢。
答案 0 :(得分: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
}
我希望这对你有帮助