前面寫了一部分關(guān)于Swift的語法學習咕痛,今天要學習的是關(guān)于IOS中數(shù)據(jù)存儲的一種存儲方式之SQLite的使用。就Swift中操作SQLite的方法做一下迄沫,一是鞏固知識點慷丽,二是為學習Swift的小伙伴提供點學習使用的SQLite的思路。扯了半會蛋了纪吮,現(xiàn)在言歸正傳俩檬,開始今天的講解。
Swift操作SQLite的流程有如下的幾個步驟:
- 建立橋接文件
- 添加library-libsqlite3.0.tbd
- 創(chuàng)建數(shù)據(jù)庫管理工具類DBManager
- 操作數(shù)據(jù)庫的簡單例子
1.建立橋接文件
1.1在用Swift使用OC中得類文件的時候碾盟,需要進行橋接棚辽,首先建一個.h的頭文件。
注意:橋接文件的命名規(guī)則:項目名-Bridging-Header.Swift
#import "SQLite3.h"
1.2 在Build-settings -> Swift Complier - Code Generaton —>Objective C Briding Herder中添加自己的橋接文件冰肴。
這樣的話屈藐,橋接文件已經(jīng)OK。
2.添加library-libsqlite3.0.tbd
在General - Linking frameworks And Library中添加library-libsqlite3.0.tbd熙尉。
這樣就表示已經(jīng)添加成功联逻。
3.用swift實現(xiàn)數(shù)據(jù)庫管理工具類DBManager.Swift
//
// DBManager.swift
// HelloSwfit
//
// Created by lidong on 16/5/22.
// Copyright ? 2016年 lidong. All rights reserved.
//
/**
*數(shù)據(jù)庫管理
*/
class DBManager {
var db: COpaquePointer = nil
private static let instance = DBManager()
// 單例 全局的數(shù)據(jù)訪問接口
class var sharedInstance: DBManager
{
return instance
}
//打開數(shù)據(jù)庫
func openDatabase(dbName: String) -> Bool
{
let documentPaths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.UserDomainMask, true)
let documnetPath = documentPaths[0]
print("documnetPath= \(documnetPath)")
let error = sqlite3_open(documnetPath+dbName, &db)
if error != SQLITE_OK {
print("SQLiteDB - failed to open DB!")
sqlite3_close(db)
}
return error == SQLITE_OK
}
//創(chuàng)建數(shù)據(jù)庫表
func createTable() -> Bool
{
let sql =
"CREATE TABLE IF NOT EXISTS T_Employee ( \n" +
"'id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, \n" +
"'name' TEXT NOT NULL, \n" +
"'age' TEXT NOT NULL, \n" +
"'department_id' TEXT );"
// 返回結(jié)果
return sqlite3_exec(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil) == SQLITE_OK
}
//執(zhí)行SQL (插入,修改检痰,刪除)
func execSql(sql: String) -> Bool
{
// 返回結(jié)果
let d = sqlite3_exec(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, nil, nil, nil) == SQLITE_OK
return d
}
func closeDb() -> Bool {
return sqlite3_close(db) == SQLITE_OK
}
func selectAll(sql:String) -> Array<Employee> {
var mArrs:Array<Employee> = []
var stmt: COpaquePointer = nil
if sqlite3_prepare_v2(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, &stmt, nil) == SQLITE_OK {
while sqlite3_step(stmt) == SQLITE_ROW {
let e = Employee()
let id1 = sqlite3_column_int(stmt, 0)
print("id = \(id1)")
let chars = UnsafePointer<CChar>(sqlite3_column_text(stmt, 1))
let str = String(CString: chars, encoding: NSUTF8StringEncoding)!
print("name \(str)")
let chars1 = UnsafePointer<CChar>(sqlite3_column_text(stmt, 2))
let str1 = String(CString: chars1, encoding: NSUTF8StringEncoding)!
print("年齡 \(str1)")
e.id = id1
e.name = str
e.age = str1
mArrs.append(e)
}
sqlite3_finalize(stmt)
closeDb()
}
return mArrs
}
/// 執(zhí)行 SQL 返回一個結(jié)果集(對象數(shù)組)
///
/// :param: sql SQL 字符串
func recordSet(sql: String) {
// 1. 準備語句
var stmt: COpaquePointer = nil
/**
1. 數(shù)據(jù)庫句柄
2. SQL 的 C 語言的字符串
3. SQL 的 C 語言的字符串長度 strlen包归,-1 會自動計算
4. stmt 的指針
5. 通常傳入 nil
*/
if sqlite3_prepare_v2(db, sql.cStringUsingEncoding(NSUTF8StringEncoding)!, -1, &stmt, nil) == SQLITE_OK {
// 單步獲取SQL執(zhí)行的結(jié)果 -> sqlite3_setup 對應(yīng)一條記錄
while sqlite3_step(stmt) == SQLITE_ROW {
// 獲取每一條記錄的數(shù)據(jù)
recordData(stmt)
}
}
}
/// 獲取每一條數(shù)據(jù)的記錄
///
/// :param: stmt prepared_statement 對象
func recordData(stmt: COpaquePointer) {
// 獲取到記錄
let count = sqlite3_column_count(stmt)
print("獲取到記錄,共有多少列 \(count)")
// 遍歷每一列的數(shù)據(jù)
for i in 0..<count {
let type = sqlite3_column_type(stmt, i)
// 根據(jù)字段的類型铅歼,提取對應(yīng)列的值
switch type {
case SQLITE_INTEGER:
print("整數(shù) \(sqlite3_column_int64(stmt, i))")
case SQLITE_FLOAT:
print("小數(shù) \(sqlite3_column_double(stmt, i))")
case SQLITE_NULL:
print("空 \(NSNull())")
case SQLITE_TEXT:
let chars = UnsafePointer<CChar>(sqlite3_column_text(stmt, i))
let str = String(CString: chars, encoding: NSUTF8StringEncoding)!
print("字符串 \(str)")
case let type:
print("不支持的類型 \(type)")
}
}
}
}
4.操作數(shù)據(jù)庫的簡單用例
//
// SQLiteViewController.swift
// HelloSwfit
//
// Created by lidong on 16/5/22.
// Copyright ? 2016年 lidong. All rights reserved.
//
import UIKit
/// SQLite的使用
class SQLiteViewController: UIViewController {
/// 數(shù)據(jù)庫名
let db_name = "/data.db3"
@IBOutlet weak var btn_submit: UIButton!
@IBOutlet weak var age: UITextField!
@IBOutlet weak var select: UIButton!
@IBOutlet weak var name: UITextField!
var dbManager : DBManager = DBManager.sharedInstance
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
print(nibName);
}
/**
加載xib
- returns: <#return value description#>
*/
convenience init() {
let nibNameOrNil = String?("SQLiteViewController")
self.init(nibName: nibNameOrNil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "SQLite學習"
let ddq = dbManager.openDatabase(db_name)
print("數(shù)據(jù)打開\(ddq)")
let sucess = dbManager.createTable()
print("表創(chuàng)建=\(sucess)")
self.btn_submit.addTarget(self, action:#selector( SQLiteViewController.submitAge(_:)), forControlEvents: .TouchUpInside)
self.btn_submit.backgroundColor = UIColor.blueColor()
self.select.addTarget(self, action:#selector( SQLiteViewController.selectAllEmp(_:)), forControlEvents: .TouchUpInside)
}
/**
提交雇員信息
- parameter btn: <#btn description#>
*/
func submitAge(btn:UIButton) {
let username:String! = self.name.text
let age_:String! = self.age.text
if (username != nil && age_ != nil){
let sql = "insert into T_Employee(name,age) values('\(self.name.text!)','\(self.age.text!)')"
print("sql: \(sql)")
let items = dbManager.execSql(sql)
Util.showToast(self, message: "插入 = \(items)")
}else{
Util.showToast(self, message: "輸入框不能為空")
return
}
}
/**
查詢所有雇員
- parameter btn: <#btn description#>
*/
func selectAllEmp(btn:UIButton) {
let sql = "select * from T_Employee"
let items = dbManager.selectAll(sql)
Util.showToast(self, message: "總數(shù) = \(items.count)")
}
/**
更新用戶信息
- parameter btn: 按鈕
- parameter en: 雇員
*/
func UpDateRmp(btn:UIButton,en:Employee) {
let sql = "update T_Employee set name = 'kkkk',age = '10' where id = 5"
let items = dbManager.execSql(sql)
Util.showToast(self, message: "更新 = \(items)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
總結(jié):SQLIte的學習基本就是從這四個步驟來實現(xiàn)箫踩。有疑問可以,在下面評論谭贪。