一、引入工具包
引入工具包libsqlite3.dylib,该工具包为C语言工具包。
二、代码操作数据库
1、创建并且链接数据库 - (void) _connectDB{//1>获取沙盒路径作为数据库创建时候的初始化路径NSString * path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
path=[path stringByAppendingPathComponent:@"new.sqlite"];
NSLog(@"%@",path);//2>如果存在则打开当前链接,如果不存在则创建if(SQLITE_OK==sqlite3_open(path.UTF8String, &sqlite)){
NSLog(@"数据库创建成功!");
}else{
NSLog(@"数据库创建失败!");
}
}
2、操作数据库 /**
* 创建表*/- (void) _createTable{
NSString*create=@"create table if not exists t_Person (id integerPRimary key autoincrement,name text,age integer,tel text)";
[self _execSql:create andTip:@"创建表操作"];
}/**
* 插入数据操作
*
* @param name 姓名
* @param age 年龄
* @param tel 电话*/- (void) _insertName:(NSString *) name andAge:(int)age andTel:(NSString *) tel{
NSString* insert=[NSString stringWithFormat:@"insert into t_Person(name,age,tel) values('%@',%d,'%@')",name,age,tel];
[self _execSql:insert andTip:@"插入操作"];
}/**
* 执行数据库操作
*
* @param sql 要执行的sql
* @param tip 要执行的操作标题*/- (void) _execSql:(NSString *) sql andTip:(NSString *) tip{char*result;if(SQLITE_OK==sqlite3_exec(sqlite, sql.UTF8String, NULL, NULL, &result)){
NSLog(@"%@成功!",tip);
}else{
NSLog(@"%@失败!",tip);
}
}
3、查询数据库 /**
* 读取数据*/- (void)_readData{//1> 定义sql语句NSString * sql=@"select id,name,age,tel from t_person";
sqlite3_stmt* stmt=NULL;//2> 检查语法的正确性if(SQLITE_OK==sqlite3_prepare_v2(sqlite, sql.UTF8String, -1, &stmt, NULL)){//3> 循环结果集取数据while(sqlite3_step(stmt)==SQLITE_ROW){//4>注意:取出来数据可以封装到集合中备用intID=sqlite3_column_int(stmt,0);constunsignedchar*name=sqlite3_column_text(stmt,1);intage=sqlite3_column_int(stmt,2);constunsignedchar*tel=sqlite3_column_text(stmt,3);
NSString* names=[NSString stringWithUTF8String:(constchar*)name];
NSString* tels=[NSString stringWithUTF8String:(constchar*)tel];
NSLog(@"%d,%@,%d,%@",ID,names,age,tels);
}
}
}
作者:杰瑞教育
出处:http://www.cnblogs.com/jerehedu/
本文版权归烟台杰瑞教育科技有限公司和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。