Swift - 操作SQLite数据库(引用SQLite3库)
生活随笔
收集整理的這篇文章主要介紹了
Swift - 操作SQLite数据库(引用SQLite3库)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SQLite輕量級數據庫在移動應用中使用非常普遍,但是目前的庫是C編寫的,為了方便使用,對SQLite相關的操作用Swift進行了封裝。這個封裝代碼使用了一個開源項目SQLiteDB,地址是:https://github.com/fahimf/sqlitedb
重要事項:SQLiteBD原作者最后只更新到Swift1.2便停止,說后面不會再更新了,如果使用Xcode7便會報錯。我這里在其基礎上進行了修改,使其支持Swift2.0。
| 1 2 3 | #import "sqlite3.h" #import <time.h> </time.h> |
3,在項目編譯屬性里引用頭文件
4,導入SQLiteDB的代碼(SQLiteDB.swift和String-Extras.swift),代碼結構如下:
5,ViewController.swift代碼
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import UIKit class ViewController: UIViewController { ????? ????var db:SQLiteDB! ????? ????@IBOutlet var txtUname: UITextField! ????@IBOutlet var txtMobile: UITextField! ????? ????override func viewDidLoad() { ????????super.viewDidLoad() ????????// Do any additional setup after loading the view, typically from a nib. ????????? ????????//獲取數據庫實例 ????????db = SQLiteDB.sharedInstance() ????????//如果表還不存在則創建表 ????????db.execute( ?????????"create table if not exists t_user(uid integer primary key,uname varchar(20),mobile varchar(20))" ????????) ????????//如果有數據則加載 ????????initUser() ????} ????override func didReceiveMemoryWarning() { ????????super.didReceiveMemoryWarning() ????????// Dispose of any resources that can be recreated. ????} ????? ????//點擊保存 ????@IBAction func saveClicked(sender: AnyObject) { ????????saveUser() ????} ????? ????//從SQLite加載數據 ????func initUser() { ????????let data = db.query("select * from t_user") ????????if data.count > 0 { ????????????//獲取最后一行數據顯示 ????????????let user = data[data.count - 1] as SQLRow ????????????txtUname.text = user["uname"]?.asString() ????????????txtMobile.text = user["mobile"]?.asString() ????????} ????} ????? ????//保存數據到SQLite ????func saveUser() { ????????let uname = self.txtUname.text! ????????let mobile = self.txtMobile.text! ????????//插入數據庫,這里用到了esc字符編碼函數,其實是調用bridge.m實現的 ????????let sql = "insert into t_user(uname,mobile) values('\(uname)','\(mobile)')" ????????println("sql: \(sql)") ????????//通過封裝的方法執行sql ????????let result = db.execute(sql) ????} } |
最新代碼下載:MySQLite2.zip
轉載于:https://www.cnblogs.com/Free-Thinker/p/4838366.html
總結
以上是生活随笔為你收集整理的Swift - 操作SQLite数据库(引用SQLite3库)的全部內容,希望文章能夠幫你解決所遇到的問題。