(十一)swift 使用SQLite
2015-12-15 10:35
465 查看
下载
下载地址: https://github.com/stephencelis/SQLite.swiftDonwload ZIP
解压缩:尽量在MacOS下完成(双击压缩包)。
引入项目
1、添加:源码中找到 “SQL.xcodeproj”, 建议在项目路径下建立文件夹“framework”,拷贝粘贴“SQLite.xcodeproj”
2、添加至项目根目录
3、添加Linked Frameworks and Libraies
项目 -> TARGETS -> Linked Frameworks and Libraies -> 点击”+”号 -> 选择”SQLite IOS” -> “Add”4、新建 MySQLite.swift
粘贴以下代码:import SQLite
internal class MySQLite
{
init() { } // 文件路径 let path = NSSearchPathForDirectoriesInDomains( .DocumentDirectory, .UserDomainMask, true ).first! // 数据库文件 var db: Connection? ; // 获取链接(不存在文件,则自动创建) private func GetConnection() ->Int { do{ db = try Connection("\(path)/db.sqlite") }catch _{ return 0; } return 1; } // 创建 ZUSER 表 private func CreateTable_USER() { GetConnection(); let ZUSER = Table("ZUSER") let id = Expression<Int64>("id") let username = Expression<String?>("username") let password = Expression<String?>("password") do { try db!.run(ZUSER.create(ifNotExists: true) { t in // CREATE TABLE "users" ( t.column(id, primaryKey: true) // "id" INTEGER PRIMARY KEY NOT NULL, t.column(username, unique: true) // "email" TEXT UNIQUE NOT NULL, t.column(password, unique: true) }) }catch _{ } } // 创建表 func CreateTable() { print("\(path)") CreateTable_USER(); }
}
// —————————————结束MySQLite.swift
5、调用测试
在AppDelegate.swift 中的application中调用
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let mySql = MySQLite(); mySql.CreateTable(); return true }
最后说明:打开Print 的目录,发现 db.splite 文件
相关文章推荐
- swift-tableView 代理方法实现点击按钮删除效果
- swift-tableView 删除行
- swift学习日记(六) 方法
- swift !?
- Swift的74标准功能
- Swift之协议( protocol)
- Swift之互斥锁的使用
- Swift学习笔记 -- 对象和类
- IOS_Swift_TYPEALIAS 和泛型接口
- Swift使用第三方库MJExtension
- 创建自注册的Swift UI 控件
- swift- 去除tableView 多余行
- Swift Swift中的反射
- swift-商品加入购物车动画
- Swift学习(持续更新)
- iOS8 用AVAudioPlayer播放音乐(Swift)
- 银行卡扫描(基于swift)
- 《从零开始学Swift》学习笔记(Day48)——类型检查与转换
- 《从零开始学Swift》学习笔记(Day48)——类型检查与转换
- 窥探Swift编程之强大的Switch