数据库应用
1.建工程,在工程中添加sql外包,如图所示,选择第二个libsqlite3.tbd
2.创建一个桥接文件
command+n创建Header File,在里面写#import <sqlite3.h>
3.获取document路径
let doc=NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let sqlPath=doc+"/Student.sqlite"
print(sqlPath)
4.打开数据库,如果没有创建
//定义为全局变量
var db:OpaquePointer?=nil
if sqlite3_open(sqlPath,&db) == SQLITE_OK {
print("数据库打开")
}
5.创建表
let sql = "create table if not exists user (id integer , name text, age integer)"
//1.数据库 2.sql语句 3.执行结果 4.参数 5.错误信息
let resdult=sqlite3_exec(db, sql, nil,nil, nil)
if resdult == SQLITE_OK {
print("创建表成功")
}else{
print("创建表失败")
}
6.sql语句操作
//插入数据
sqlite3_exec(db, "insert into user(id,name,age) values(1,'小明',12)",nil, nil, nil)
if resdult==SQLITE_OK{
print("插入成功")
}else{
print("插入失败")
}
//更新
let updateSql="update user set name='小粒' where name='小明'";
let resdult1=sqlite3_exec(db, updateSql, nil, nil, nil)
if resdult1==SQLITE_OK{
print("更新成功")
}else{
print("更新失败")
}
//删除
let deleteSql="delete from user where name='小粒'";
let resdult2=sqlite3_exec(db,deleteSql, nil, nil, nil)
if resdult2==SQLITE_OK{
print("删除成功")
}else{
print("删除失败")
}
//查找
let searchSql="select * from user where name=?"
//1.数据库 2.sql 3.sql长度 -1 自动计算 4.伴随指针 5.nil
var stmt:OpaquePointer?=nil
let resdult3=sqlite3_prepare_v2(db, searchSql,-1, &stmt, nil)
//给?赋值
//1.伴随指针 2.?在第几位 从1开始 3.绑定的值
sqlite3_bind_int(stmt, 2, 1)
//将SQLITE_TRANSIENT定义为全局变量
private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
sqlite3_bind_text(stmt, 1, "小明", -1, SQLITE_TRANSIENT)
if resdult3==SQLITE_OK{
print("预编译成功")
}else{
print("预编译失败")
}
//执行sql
while sqlite3_step(stmt) == SQLITE_ROW{
//取值
let id=sqlite3_column_int(stmt, 0)
let cname=sqlite3_column_text(stmt, 1)
let name=String(cString: cname!)
let age=sqlite3_column_int(stmt,2)
print("id=\(id),name=\(name),age=\(age)")
//把对象装到数组中
}
//释放stmt
sqlite3_finalize(stmt)
//关闭数据库
sqlite3_close(db)