下面是代码:
//sqlite 常用语句
- [selfopenDataBase];
- [selfcreateTable];
- [selfinsertTable];
- [selfqueryTable];
- [selfdeleteTable];
- [selfqueryTable];
实现:
//opendatabase
- -(void)openDataBase
- {
- NSArray*documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
- NSString*databaseFilePath=[[documentsPathsobjectAtIndex:0]stringByAppendingPathComponent:@"db.sql"];
- if(sqlite3_open([databaseFilePathUTF8String],&database)==sqlITE_OK)
- {
- NSLog(@"opensqlitedbok.");
- }
- else
- {
- NSLog(@"cannotopensqlitedb");
- //closedatabase
- sqlite3_close(database);
- }
- }
//createtable
- -(void)createTable
- {
- char*errorMsg;
- constchar*createsql="createtableifnotexistspersons(idintegerprimarykeyautoincrement,nametext)";
-
- if(sqlite3_exec(database,createsql,@H_403_228@NULL,&errorMsg)==sqlITE_OK)
- {
- NSLog(@"createok.");
- }
- else
- {
- NSLog(@"cannotcreatetable");
- [selfErrorReport:(NSString*)createsql];
- }
- }
-
//inserttable
- -(void)insertTable
- {
- char*errorMsg;
- constchar*insertsql="insertintopersons(name)values('田周辉')";
- if(sqlite3_exec(database,insertsql,&errorMsg)==sqlITE_OK)
- {
- NSLog(@"insertok.");
- }
- else
- {
- NSLog(@"cannotinsertittotable");
- [selfErrorReport:(NSString*)insertsql];
- }
- }
//error
- -(void)ErrorReport:(NSString*)item
- {
- char*errorMsg;
- if(sqlite3_exec(database,(constchar*)item,&errorMsg)==sqlITE_OK)
- {
- NSLog(@"%@ok.",item);
- }
- else
- {
- NSLog(@"error:%s",errorMsg);
- sqlite3_free(errorMsg);
- }
- }
//query
-(void)queryTable
{
constchar*selectsql="selectid,namefrompersons";
sqlite3_stmt*statement;
if(sqlite3_prepare_v2(database,selectsql,-1,&statement,nil)==sqlITE_OK)
{
NSLog(@"selectok.");
while(sqlite3_step(statement)==sqlITE_ROW)//sqlITE_OKsqlITE_ROW
{
int_id=sqlite3_column_int(statement,0);
NSString*name=[[NSStringalloc]initWithCString:(char*)sqlite3_column_text(statement,1)encoding:NSUTF8StringEncoding];
NSLog(@"row>>id%i,name>>%@",_id,name);
}
}
else
{
//error
[selfErrorReport:(NSString*)selectsql];
}
sqlite3_finalize(statement);
}
//delete
-(void)deleteTable
{
char*errorMsg;
[selfopenDataBase];
constchar*sql="DELETEFROMpersonswhereid=24";
if(sqlite3_exec(database,sql,&errorMsg)==sqlITE_OK)
{
NSLog(@"deleteok.");
}
else
{
NSLog(@"cannotdeleteit");
[selfErrorReport:(NSString*)sql];
}
}
命令行:
sqlite3database//创建数据库
- cratetabletableFile(idsmallint,file_namevarchar(256),up_statesmallint,file_sizesmallint);//创建一个表格
- insertintotableFilevalues(1,"200110101.rcu",100,4500);//插入数据
- 如何访问sqlite3数据库 ?
- sqlite3_open//打开数据库
- sqlite3_prepare//将UTF-8格式的sql语句转换为指向已备语句的指针
- sqlite3_column_string//返回某一行的字符串
- sqlite3_finalize//删除一条已备语句
- sqlite3_close//关闭数据库
sourcecode
- -(id)lookupSingularsql:(NSString*)sqlforType:(NSString*)rettype{
- sqlite3_stmt*statement;
- idresult;
- if(statement=[selfprepare:sql]){
- if(sqlite3_step(statement)==sqlITE_ROW){
- if([rettypecompare:@"text"]==NSOrderedSame){
- chartemp_buf[256];
- memset(temp_buf,256);
- sprintf(temp_buf,"%s%s%s%s",(char*)sqlite3_column_text(statement,0),(char*)sqlite3_column_text(statement,1),
- (char*)sqlite3_column_text(statement,2),3));
- result=[NSStringstringWithUTF8String:temp_buf];
- //result=[NSStringstringWithUTF8String:(char*)sqlite3_column_text(statement,0)];
- }elseif([rettypecompare:@"integer"]==NSOrderedSame){
- result=(id)sqlite3_column_int(statement,0);
- }
- }
- }
- sqlite3_finalize(statement);
- returnresult;
- }
应该有个成员变量,比如我的代码:
- @interfaceDetailViewController:UIViewController{
- UIPopoverController*popoverController;
- UIToolbar*toolbar;
- iddetailItem;
- UILabel*detailDescriptionLabel;
- sqlite3*database;
打开数据库
sqlite数据库是文件数据库,是保存在文件系统中的。因此需要知道文件保存到哪里,可参见iOS中对文件的操作。比如本文保存到Documents目录下。代码:
- NSArray*documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,YES);
- NSString*databaseFilePath=[[documentsPathsobjectAtIndex:0]stringByAppendingPathComponent:@"mydb"];
- if(sqlite3_open([databaseFilePathUTF8String],&database)==sqlITE_OK)
- {
- NSLog(@"opensqlitedbok.");
- }
通过ssh查看Documents目录,发现mydb文件已经创建。sqlite的策略是如果有该文件就打开,如果没有就创建文件,也就是创建数据库。
这里要注意,使用的是C语法,sqlite3_open传入的是database的地址。
关闭数据库
数据库使用完毕后,要关闭,比如退出应用的时候:
- -(void)viewDidUnload{
- //Release@H_403_228@anyretainedsubviewsofthemainview.
//e.g.self.myOutlet=nil;
sqlite3_close(database);
self.popoverController=nil;
}
建表语句
数据库打开以后,如果没有表,建表:
- char*errorMsg;
- constchar*createsql="createtableifnotexistspersons(idintegerprimarykeyautoincrement,nametext)";
- if(sqlite3_exec(database,&errorMsg)==sqlITE_OK){
- NSLog(@"createok.");
- }
这里要特别注意errorMsg传的是地址,因为该函数要通过地址引用来写报错字符信息。
向表中插入记录
和建表语句类似:
- constchar*insertsql="insertintopersons(name)values(‘张三’)";
- if(sqlite3_exec(database,&errorMsg)==sqlITE_OK){
- NSLog(@"insertok.");
- }
错误信息的处理
如果在多个地方使用errorMsg,那么每次使用完毕要清空一下字串,比如这样:
- if(sqlite3_exec(database,&errorMsg)==sqlITE_OK){
- NSLog(@"createok.");
- }else{
- NSLog(@"error:%s",errorMsg);
- sqlite3_free(errorMsg);
- }
查询结果集
结果集的查询,需要用到statement:
- constchar*selectsql="selectid,namefrompersons";
- sqlite3_stmt*statement;
- if(sqlite3_prepare_v2(database,nil)==sqlITE_OK){
- NSLog(@"selectok.");
- }
- while(sqlite3_step(statement)==sqlITE_ROW){
- int_id=sqlite3_column_int(statement,0);
- char*name=(char*)sqlite3_column_text(statement,1);
- NSLog(@"row>>id%i,name%s",name);
- }
- sqlite3_finalize(statement);
不过这里有个问题,看看打印的日志:
乱码。因为直接用的char类型来做的。
解决办法是,用nsstring替代char:
- while(sqlite3_step(statement)==sqlITE_ROW){
- int_id=sqlite3_column_int(statement,0);
- NSString*name=[[NSStringalloc]initWithCString:(char*)sqlite3_column_text(statement,1)encoding:NSUTF8StringEncoding];
- NSLog(@"row>>id%i,name%@",name);
- }
char生成nsstring的时候做一次显式的编码。问题解决:
这说明:
写入数据库,用char的方式没有问题,写入数据库的编码是对的;
从库中取出,可能默认使用ascii解码,造成显示乱码。
使用sqlite c api,要经常参考官方函数文档:http://www.sqlite.org/c3ref/funclist.html
原文链接:https://www.f2er.com/sqlite/201008.html