下载
下载地址: https://github.com/stephencelis/SQLite.swift
Donwload 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 文件