// 建立數據庫 // 文件路徑 : // 1.獲取數據庫的存放路徑(沙盒中) let filePath = "/Users/xiaomage/Desktop/123.sqlite" let cString = filePath.cStringUsingEncoding(NSUTF8StringEncoding)! // 2.定義數據庫對象(後面還要用,定義一個屬性替代) // var db : COpaquePointer = nil // 3.打開/建立 數據庫對象 if sqlite3_open(cString, &db) == SQLITE_OK { print("建立/打開數據庫成功") } else { print("失敗") } }
CREATE TABLE IF NOT EXISTS '表名' (
'字段名' 類型(INTEGER, REAL, TEXT, BLOB)
NOT NULL 不容許爲空
PRIMARY KEY 主鍵
AUTOINCREMENT 自增加,
'字段名2' 類型,
...
DROP TABLE IF EXISTS '表名';
1 // 1.獲取要執行的SQL語句 2 let createTableSQL = "DROP TABLE IF EXISTS t_student;" 3 4 // 2.執行語句 5 if sqlite3_exec(db, createTableSQL.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil) == SQLITE_OK { 6 print("刪除表成功") 7 } else { 8 print("刪除表失敗") 9 } 10 }
class SQLiteManager { // 設計單例對象 static let shareInstance : SQLiteManager = SQLiteManager() // 數據庫對象 var db : COpaquePointer = nil } // MARK:- 打開數據庫的操做 extension SQLiteManager { func openDB(filePath : String) -> Bool { // 1.將Swift字符串轉成C語言的字符串 let cString = filePath.cStringUsingEncoding(NSUTF8StringEncoding)! // 3.打開/建立數據庫對象 return sqlite3_open(cString, &db) == SQLITE_OK } } // MARK:- 執行SQL語句 extension SQLiteManager { func execSQL(sqlString : String) -> Bool { // 1.將Swift字符串轉成C語言的字符串 let cSQLString = sqlString.cStringUsingEncoding(NSUTF8StringEncoding)! // 2.執行語句 return sqlite3_exec(db, cSQLString, nil, nil, nil) == SQLITE_OK } }
INSERT INTO 't_student' (name, age, height) VALUES ('why', 18, 1.88);
// 1.插入數據(獲取插入語句) let insertSQL = "INSERT INTO t_student (name, age, height) VALUES ('why', 18, 1.88);" // 2.執行語句 SQLiteManager.shareInstance.execSQL(insertSQL)
UPDATE 't_student' SET 字段 = '值' WHERE 條件判斷;
// 1.獲取更新語句 let updateSQL = "UPDATE t_student SET name = 'yz';" // 2.執行語句 SQLiteManager.shareInstance.execSQL(updateSQL)
DELETE FROM t_student;
// 1.獲取刪除語句 let deleteSQL = "DELETE FROM t_student;" // 2.執行語句 SQLiteManager.shareInstance.execSQL(deleteSQL)
// 模擬從網絡服務器中請求到不少數據(實際中數據是網絡來的,這裏本身寫模擬) for _ in 0..<100 { let name = "zs\(arc4random_uniform(100))" let age = Int(10 + arc4random_uniform(10)) let height = 1 + Double(arc4random_uniform(10)) / 10.0 let stu = Student(name: name, age: age, height: height) stus.append(stu) }
1 class Student: NSObject { 2 var name : String = "" 3 var age : Int = 0 4 var height : Double = 0.0 5 6 init(name : String, age : Int, height : Double) { 7 self.name = name 8 self.age = age 9 self.height = height 10 } 11 } 12 13 extension Student { 14 func insertDB() { 15 // 1.插入數據(獲取插入語句) 16 let insertSQL = "INSERT INTO t_student (name, age, height) VALUES ('\(name)', \(age), \(height));" 17 // 2.執行語句 18 SQLiteManager.shareInstance.execSQL(insertSQL) 19 } 20 }
for stu in stus { stu.insertDB() }
1 dispatch_async(dispatch_get_global_queue(0, 0)) { 2 //獲取插入數據開始時間 3 let startTime = CACurrentMediaTime() 4 // 開啓事務 5 let startSQL = "BEGIN TRANSACTION;" 6 SQLiteManager.shareInstance.execSQL(startSQL) 7 8 for stu in self.stus { 9 stu.insertDB() 10 } 11 //關閉事務 12 let commitSQL = "COMMIT TRANSACTION;" 13 SQLiteManager.shareInstance.execSQL(commitSQL) 14 //獲取插入數據結束時間 15 let endTime = CACurrentMediaTime() 16 //獲取插入數據耗時 17 print(endTime - startTime) 18 } 19 }
1.查詢語句
1 // 1.獲取查詢語句 2 let querySQL = "SELECT * FROM t_student LIMIT 30, 30;"; 3 4 // 2.執行語句 (執行語句封裝到了一個方法裏面) 5 guard let dictArray = SQLiteManager.shareInstance.querySQL(querySQL) else { 6 return 7 } 8 9 // 3.遍歷數組 10 var tempArray = [Student]() 11 for dict in dictArray { 12 // 字典轉模型 13 tempArray.append(Student(dict: dict)) 14 } 15 16 for stu in tempArray { 17 print(stu.name, stu.age) 18 } 19 20 //執行語句代碼實現 21 func querySQL(querySQL : String) -> [[String : NSObject]]? { 22 // 0.將Swift字符串轉成C語言字符串 23 let cString = querySQL.cStringUsingEncoding(NSUTF8StringEncoding)! 24 25 // 1.定義遊標(指針) 26 var stmt : COpaquePointer = nil 27 28 // 2.給遊標賦值 29 // 1> 參數一: 數據庫對象 30 // 2> 參數二: SQL語句 31 // 3> 參數三: 該SQL語句的長度 -1 --> 系統自動計算 32 // 4> 參數四: 遊標的地址 33 guard sqlite3_prepare_v2(db, cString, -1, &stmt, nil) == SQLITE_OK else { 34 return nil 35 } 36 37 // 3.取出全部的數據 38 // 3.1.定義字典數組 39 var dictArray = [[String : NSObject]]() 40 41 // 3.2.判斷是否有該條數據 42 while sqlite3_step(stmt) == SQLITE_ROW { 43 // 3.3.獲取字段的個數 44 let count = sqlite3_column_count(stmt) 45 // 3.4.定義字典 46 var dict = [String : NSObject]() 47 // 3.5.遍歷每個字典 48 for i in 0..<count { 49 // 3.6.取出該列的鍵 50 let ckey = sqlite3_column_name(stmt, i) 51 guard let key = String(UTF8String : ckey) else { 52 continue 53 } 54 // 3.7.取出該列的值 55 let cvalue = UnsafePointer<Int8>(sqlite3_column_text(stmt, i)) 56 //將c語言字符串轉成swift字符串 57 let value = String(UTF8String : cvalue) 58 59 // 3.8.將鍵值對放入到字典中 60 dict[key] = value 61 } 62 // 3.9.將字典放入到數組中 63 dictArray.append(dict) 64 } 65 return dictArray 66 } 67 }
private lazy var db : FMDatabase = FMDatabase(path: "/Users/lgp/Desktop/321.sqlite") // 建立FMDatabase對象 // 打開/建立數據 if db.open() { print("打開成功") } else { print("失敗") }
// 1.獲取建立表的語句 let createSQL = "INSERT INTO t_person (name, age, height) VALUES ('why', 18, 1.88);" // 2.執行語句 db.executeUpdate(createSQL, withArgumentsInArray: nil)
1 func querySQL(querySQL : String) -> [[String : NSObject]]? { 2 // 0.判斷db是否有值 db定義爲屬性 3 guard let db = db else { 4 return nil 5 } 6 // 1.執行查詢語句 結果爲集合 7 let results = db.executeQuery(querySQL, withArgumentsInArray: nil) 8 9 // 2.獲取數據 10 // 2.0.定義數據 11 var dictArray = [[String : NSObject]]() 12 13 // 2.1.判斷結果集中是否有內容 14 while results.next() { 15 16 let count = results.columnCount() 17 18 var dict = [String : NSObject]() 19 20 for i in 0..<count { 21 let key = results.columnNameForIndex(i) 22 let value = results.stringForColumnIndex(i) 23 24 dict[key] = value 25 } 26 dictArray.append(dict) 27 } 28 return dictArray 29 }