2015-08-20 95 views
2

我使用的是SQLite.swift,我使用SQLite.swift演示中的這些代碼。爲什麼將數據保存到SQLite數據庫不適用於Swift 2?

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 <- "[email protected]")) 
     for user in db.prepare(users) { 
      print("id: \(user[id]), email: \(user[email])") 
     } 
    } 
} 

我第一次運行它,則輸出是:

("SELECT * FROM \"users\"", []) 
id: 1, email: [email protected] 

然後我除去線17(try! db.run(users.insert(email <- "[email protected]")))並再次運行,調試器輸出改變爲:

("SELECT * FROM \"users\"", []) 

看起來像[email protected]沒有保存到數據庫。那麼我做錯了什麼?或者如何將它保存到SQLite數據庫中?

P.S.我正在使用Xcode 7 beta 5,Swift 2.0

+0

請檢查數據庫。該記錄在數據庫中可用? –

+0

我不知道位於@iAshish的數據庫位於何處 – David

+0

您已經給出了將數據庫存儲在文檔目錄路徑的路徑嗎? @大衛 ? –

回答

0

viewDidLoad首先創建表,然後插入。

當表已經存在時,我不知道表create函數的行爲,但如果它不會在您身上拋出任何錯誤,它可能會再次重新創建表。如果是這種情況,在插入註釋後調用viewDidLoad之後,可能會得到一個新的空白表。

嘗試更改邏輯,確保每次都不重新創建表。

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

你可能有這樣的事情(當然其他人可以提高代碼):

  1. 創建表格模型:

    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 == 「[email protected]」) 
    
        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 
    } 
    } 
    
  2. 創建數據庫幫手

    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」) 
        } 
    } 
    } 
    
  3. 最後(在這裏你不需要導入SQLite的)。

    class ViewController: UIViewController { 
    override func viewDidLoad() { 
        super.viewDidLoad() 
    
        TUsers.addUser(「[email protected]」, 「John Capuchon」) 
    
        let users = TUsers.getAllUsers() 
    
        for user in users { 
         // do something 
        } 
    } 
    

    }