2017-09-07 47 views
0

經驗的開發人員在這裏......但有些新的雨燕與SQLite.swift明確的新手...簡單的存儲/檢索BLOB或數據(NSKeyArchive也許一類)

我試圖讓我的手在iOS應用程序中使用SQLite - 所以我創建了一個簡單的應用程序,以確保我獲得了基礎知識...一切都很順利,直到我存儲和檢索數據對象(即類對象)爲止...

這裏是我的代碼:

//********************************************************************** 
    //** 
    //** Create/Open database connection 
    //** 
    //********************************************************************** 
    let dbPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! 
    let db: Connection = try! Connection("\(dbPath)/stickis.sqlite3") 

    let dbTable = Table("testtbl") 
    let id = Expression<Int64>("id") 
    let boolfld = Expression<Bool>("boolfld") 
    let int64fld = Expression<Int64>("int64fld") 
    let stringfld = Expression<String>("stringfld") 
    let blobfld = Expression<SQLite.Blob?>("blobfld") // optional due to ? 

    //********************************************************************** 
    //* 
    //* Drop table if it exists 
    //* 
    //********************************************************************** 
    try! db.run(dbTable.drop(ifExists: true)) 

    //********************************************************************** 
    //** 
    //** Create/Open Table 
    //** 
    //********************************************************************** 
    do 
    { 
     try db.run((dbTable.create(ifNotExists: true) 
     { 
      t in 
      t.column(id, primaryKey: true) 
      t.column(boolfld) 
      t.column(int64fld) 
      t.column(stringfld) 
      t.column(blobfld) 
      }) 
     ) 
    } 
    catch 
    { 
     print("Failed to create sticki table") 
    } 

    //********************************************************************** 
    //** 
    //** Add Record 1 
    //** 
    //********************************************************************** 
    do 
    { 
     let testblob: Blob = windowcontent() 
     let rowid = try db.run(dbTable.insert(boolfld <- true, int64fld <- 1963, stringfld <- "unknown", blobfld <- testblob)) 
     print("inserted id: \(rowid)") 
    } 
    catch 
    { 
     print("insertion failed: \(error)") 
    } 

    //********************************************************************** 
    //** 
    //** Add Record 2 
    //** 
    //********************************************************************** 
    do 
    { 
     let rowid = try db.run(dbTable.insert(boolfld <- true, int64fld <- 1972, stringfld <- "David")) 
     print("inserted id: \(rowid)") 
    } 
    catch 
    { 
     print("insertion failed: \(error)") 
    } 

    //********************************************************************** 
    //** 
    //** Update Record 1 
    //** 
    //********************************************************************** 
    let rec2updt = dbTable.filter(id == 1) 
    do 
    { 
     if try db.run(rec2updt.update(stringfld <- "TJ")) > 0 
     { 
      print("updated to TJ") 
     } 
     else 
     { 
      print("record not found") 
     } 
    } 
    catch 
    { 
     print("update failed") 
    } 

    //********************************************************************** 
    //** 
    //** Query Particular Record using filter 
    //** 
    //********************************************************************** 
    let tjFilter = dbTable.filter(int64fld == 1964) 
    for dataRec in try! db.prepare(tjFilter) 
    { 
     print("id: \(dataRec[id]), stringfld: \(dataRec[stringfld])") 
    } 

    //********************************************************************** 
    //** 
    //** Query All Records 
    //** 
    //********************************************************************** 
    for dataRec in try! db.prepare(dbTable) 
    { 
     print("id: \(dataRec[id]), stringfld: \(dataRec[stringfld])") 
    } 

    //********************************************************************** 
    //** 
    //** Delete Records 
    //** 
    //********************************************************************** 
    try! db.run(dbTable.delete()) 

一切都工作得很好˚F或者我....直到我說「添加記錄1」的註釋塊下面的這行...

let testblob: Blob = windowcontent() 

windowcontent()是一個類(或者可能是一個結構),我想「存檔「並保存...我使用Blob存儲它的原因是存儲的對象類型可能有幾個不同的類。

我也試過這樣:

 let testdata: Data = Data() 
     let testblob: Blob = testdata as Blob 

,並獲得無法預期的錯誤,以將數據轉換成團塊

沒有人有從SQLite.Blob分配和檢索數據/一個簡單的例子他們會與我分享?

另外,側面的話題,有沒有一個好的地方,我可以分享我的「基礎」iOS示例代碼,一旦我全部運行它?假設其他一些新手可能會來,它可以使生活更輕鬆。

+0

僅供參考......沒想到「讓testblob:斑點= windowcontent()」,以實際工作......這是最好的辦法,我只是說明我是想代碼...所以請不要糾結於嘗試調試該行的語法...... – tj4shee

+0

找出部分解決方案....使用Blob(字節:[UInt8](xxx))將數據轉換爲blob。 ..其中xxx是數據對象....現在想出如何將數據轉換回數據... – tj4shee

+0

解決方案的第二部分 - 使用Blob.bytes完成從Blob到數據的轉換...請參閱我輸入的代碼作爲答案。 – tj4shee

回答

0

這裏是運行的代碼,回答我的問題。請參閱「使用過濾器查詢特定記錄」一節,瞭解從Blob轉換回字符串的位置。

override func viewDidLoad() 
{ 
    super.viewDidLoad() 
    // Do any additional setup after loading the view. 


    //********************************************************************** 
    //** 
    //** Create/Open database connection 
    //** 
    //********************************************************************** 

    // dbpath is where we want the sqlite file to reside... in this case we are using the documents directory 
    let dbPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! 

    // the filename we are giving our database is "testdb.sqlite3" - it can be what ever you like. If the file exists, it opens it as a database, if it does not exist, it will create it and then open it. 
    let db: Connection = try! Connection("\(dbPath)/testdb.sqlite3") 

    // defining the name of the SQLite table we want to use as well as the field names we want to create in the table. In this case, we are creating one of each major type of fields - Bool, Long Int, String, Blob 
    let dbTable = Table("testtbl") 
    let id = Expression<Int64>("id") 
    let boolfld = Expression<Bool>("boolfld") 
    let int64fld = Expression<Int64>("int64fld") 
    let stringfld = Expression<String>("stringfld") 
    let blobfld = Expression<SQLite.Blob?>("blobfld") // Blob field is optional due to SQLite.Blob? - remove the ? to make it require "Not Null" 

    //********************************************************************** 
    //* 
    //* Drop table if it exists 
    //* 
    //********************************************************************** 
    // Deleting the table if it exists - this is simply to allow the program to be rerun and start by creating a new table 
    try! db.run(dbTable.drop(ifExists: true)) 

    //********************************************************************** 
    //** 
    //** Create/Open Table 
    //** 
    //********************************************************************** 
    do 
    { 
     // create the table with the following fields... 
     try db.run((dbTable.create(ifNotExists: true) 
     { 
      t in 
      // the fields in our table... 
      t.column(id, primaryKey: true) 
      t.column(boolfld) 
      t.column(int64fld) 
      t.column(stringfld) 
      t.column(blobfld) 
      }) 
     ) 
    } 
    catch 
    { 
     // should not get to this, but if it does, you can expect the remainder of the app to fail also. 
     print("Failed to create sticki table") 
    } 

    //********************************************************************** 
    //** 
    //** Add Record 1 
    //** 
    //********************************************************************** 
    do 
    { 
     // setup a Data var and then save it as an SQLite.Blob 
     let testdata: Data = "foo".data(using: .utf8)! //Data() 
     let testblob: Blob = Blob(bytes: [UInt8](testdata)) 

     // insert a new record into the database... the function will return the rowID of the newly inserted record. 
     let rowid = try db.run(dbTable.insert(boolfld <- true, int64fld <- 1963, stringfld <- "unknown", blobfld <- testblob)) 

     print("inserted id: \(rowid)") 
    } 
    catch 
    { 
     print("insertion failed: \(error)") 
    } 

    //********************************************************************** 
    //** 
    //** Add Record 2 
    //** 
    //********************************************************************** 
    do 
    { 
     // Adding a 2nd record to the database - no Blob field this time 
     let rowid = try db.run(dbTable.insert(boolfld <- true, int64fld <- 1972, stringfld <- "David")) 
     print("inserted id: \(rowid)") 
    } 
    catch 
    { 
     print("insertion failed: \(error)") 
    } 

    //********************************************************************** 
    //** 
    //** Update Record 1 
    //** 
    //********************************************************************** 

    // Setup filter to get record "WHERE id == 1" 
    let rec2updt = dbTable.filter(id == 1) 
    do 
    { 
     // db.run will return the # of records updated - must be > 0 (actually, == 1) 
     if try db.run(rec2updt.update(stringfld <- "TJ")) > 0 
     { 
      print("updated to TJ") 
     } 
     else 
     { 
      print("record not found") 
     } 
    } 
    catch 
    { 
     print("update failed") 
    } 

    //********************************************************************** 
    //** 
    //** Query Particular Record using filter 
    //** 
    //********************************************************************** 

    // Setup filter to get record "WHERE int64fld == 1963" 
    let tjFilter = dbTable.filter(int64fld == 1963) 

    // Run using filter and print out results (should only be 1 rec in our case) 
    for dataRec in try! db.prepare(tjFilter) 
    { 
     // Convert Blob back to String 
     let tmpStr: String = String(bytes: dataRec[blobfld]!.bytes, encoding: .utf8)! 
     print("id: \(dataRec[id]), stringfld: \(dataRec[stringfld]), blobfld: \(tmpStr)") 
    } 

    //********************************************************************** 
    //** 
    //** Query All Records 
    //** 
    //********************************************************************** 

    // Prints all records in database 
    for dataRec in try! db.prepare(dbTable) 
    { 
     print("id: \(dataRec[id]), stringfld: \(dataRec[stringfld])") 
    } 

    //********************************************************************** 
    //** 
    //** Delete Records 
    //** 
    //********************************************************************** 

    // Deletes ALL records in the table (use a filter to delete individual records) 
    try! db.run(dbTable.delete()) 

} 

override func didReceiveMemoryWarning() 
{ 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
相關問題