// 先导入sqlite
// 创建sqlite对象的类属性
static sqlite3 *_db;
+(void)initialize {
// 1. 获取沙盒中数据库文件的地址
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@”student.sqlite”];
_db = NULL;
// 2.打开数据库
int result = sqlite3_open(path.UTF8String, &_db);
if (result == SQLITE_OK) {
NSLog(@"数据库打开成功!");
char *errorMssage = NULL;
const char *sql = "create table if not exists t_student (id integer primary key autoincrement not null, name text unique);";
3.创建表
int result = sqlite3_exec(_db, sql, NULL, NULL, &errorMssage);
if (result == SQLITE_OK) {
NSLog(@"创建学生表成功!");
}
else
{
NSLog(@"创建学生表失败!%s", errorMssage);
}
}
else
{
NSLog(@"数据库打开失败!");
}
}
// 添加数据
- (void)add {
const char *sql = “insert into t_student (name) values (‘成龙’)”;
char *errmsg = NULL;
int result = sqlite3_exec(_db, sql, NULL, NULL, &errmsg);
if (result == SQLITE_OK) {
NSLog(@”插入数据成功!”);
}
else
{
NSLog(@”插入数据失败!%s”, errmsg);
}
}
// 删除数据
- (void)del {
const char *sql = “delete from t_student”;
char *errmsg = NULL;
int result = sqlite3_exec(_db, sql, NULL, NULL, &errmsg);
if (result == SQLITE_OK) {
NSLog(@”删除数据成功”);
}
else
{
NSLog(@”删除数据失败:%s”, errmsg);
}
}
// 更新数据
- (void)update {
const char *sql = “update t_student set name = ‘张珊’ where id = 1;”;
char *errmsg = NULL;
int result = sqlite3_exec(_db, sql, NULL, NULL, &errmsg);
if (result == SQLITE_OK) {
NSLog(@”修改数据成功!”);
}
else
{
NSLog(@”修改数据失败:%s”, errmsg);
}
}
// 查询数据
- (void)query {
// 1.sql语句
const char *sql = “select id, name form c_student order by id desc”;
// 2.stmt结果集容器
sqlite3_stmt *stmt = NULL;
// 3.检查sql语句的合法性(-1代表自动计算sql语句的长度)
int result = sqlite3_prepare(_db, sql, -1, &stmt, NULL);
if (result == SQLITE_OK) {
NSLog(@"语句合法");
// 获得每行数据
while (sqlite3_step(stmt) == SQLITE_ROW) {
// 获得某列的数据
int cid = sqlite3_column_int(stmt, 0);
const unsigned char *cname = sqlite3_column_text(stmt, 1);
NSLog(@"id:%d,name:%s", cid, cname);
}
}
else
{
NSLog(@"语句非法");
}
}