我正在使用SQLite.swift,我正在使用SQLite.swift演示中的这些代码。
import UIKit
import SQLite
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let db = try! Connection()
let users = Table("users")
let id = Expression<Int64>("id")
let email = Expression<String>("email")
let name = Expression<String?>("name")
try! db.run(users.create { t in
t.column(id, primaryKey: true)
t.column(email, unique: true, check: email.like("%@%"))
t.column(name)
})
try! db.run(users.insert(email <- "alice@mac.com"))
for user in db.prepare(users) {
print("id: \(user[id]), email: \(user[email])")
}
}
}
我第一次运行它时,输出是:
("SELECT * FROM \"users\"", [])
id: 1, email: alice@mac.com
然后我删除了第17行(try! db.run(users.insert(email <- "alice@mac.com"))
)并再次运行,调试器输出更改为:
("SELECT * FROM \"users\"", [])
看起来alice@mac.com
没有保存到数据库。那么我做错了什么?或者如何将其保存到SQLite数据库中?
P.S。我正在使用Xcode 7 beta 5,Swift 2.0
答案 0 :(得分:3)
let db = try! Connection()
创建一个内存中数据库,您可以从API文档中看到:
/// Initializes a new SQLite connection.
///
/// - Parameters:
///
/// - location: The location of the database. Creates a new database if it
/// doesn’t already exist (unless in read-only mode).
///
/// Default: `.InMemory`.
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Returns: A new database connection.
public init(_ location: Location = .InMemory, readonly: Bool = false) throws
数据不会持久保存到文件中,并且数据库始终是最初的 空。
对于持久性数据库,请使用
/// Initializes a new connection to a database.
///
/// - Parameters:
///
/// - filename: The location of the database. Creates a new database if
/// it doesn’t already exist (unless in read-only mode).
///
/// - readonly: Whether or not to open the database in a read-only state.
///
/// Default: `false`.
///
/// - Throws: `Result.Error` iff a connection cannot be established.
///
/// - Returns: A new database connection.
public convenience init(_ filename: String, readonly: Bool = false) throws
而是,例如
// Compute file path for database in Documents directory:
let docsDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
let dbPath = (docsDir as NSString).stringByAppendingPathComponent("database.sqlite")
do {
let db = try Connection(dbPath)
// ... use database
} catch (error) {
// Could not create or open database, print error
}
答案 1 :(得分:0)
viewDidLoad
首先创建表,然后插入。
当表已经存在时,我不知道表create function的行为,但是如果它没有给你带来任何错误,它可能会再次重新创建表。如果是这种情况,在调用插入注释掉的viewDidLoad
之后,您可能最终得到一个全新的空白表。
尝试更改逻辑,确保每次都不重新创建表。
答案 2 :(得分:0)
你可以拥有这样的东西(显然其他人都可以改进代码):
创建表格模型:
class TUsers {
static let TABLE_NAME : String = “users”
static let ID = Expression<Int64>("id")
static let EMAIL = Expression<String>(“email”)
static let NAME = Expression<String>(“name”)
class func addUser(email : String!, name : String!) -> Bool{
let users = Table(TABLE_NAME)
do {
try DBHelper.instance.db.run(users.insert(
TUsers.EMAIL <- email,
TUsers.NAME <- name
))
return true
} catch {
print("Insert failed")
return false
}
}
class func getAllUsers() -> [User] { // you must create the model user
let users = Table(TUsers.TABLE_NAME)
let query = users.select(*)
//.filter(TUsers.EMAIL == “whatever@pomberobota.com”)
var listOfUsers : [Users] = []
for user in DBHelper.instance.db.prepare(query) {
// Do whatever you need to instantiate the model User
listOfUsers.append(User(email: users[TUsers.EMAIL], name: users[TUsers.NAME])
}
return listOfUsers
}
}
创建数据库助手
class DBHelper {
static let instance = DBHelper()
var db : Connection
init() {
do {
self.db = try Connection("\(Util.getDBPath())/db.sqlite3")
createTablesIfNotExists()
} catch {
print("Could not create a connection to database")
}
}
func createTablesIfNotExists() {
let users = Table(TUsers.TABLE_NAME)
do {
try db.run(logs.create(ifNotExists: true) { t in
t.column(TUsers.ID, primaryKey: true)
t.column(TUsers.EMAIL)
t.column(TUsers.NAME)
})
} catch {
print(“Could not create table users”)
}
}
}
最后(这里你不需要导入SQLite)。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
TUsers.addUser(“user@ndetavysho.com”, “John Capuchon”)
let users = TUsers.getAllUsers()
for user in users {
// do something
}
}
}