您的位置:首页 > 移动开发 > Swift

(十一)swift 使用SQLite

2015-12-15 10:35 465 查看

下载

下载地址: 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 文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: