iPhone开发【二十四】数据持久化总结之第4篇—sqlite3数据库

来源:互联网 发布:中文域名好吗 编辑:程序博客网 时间:2024/04/25 20:26

转载请注明出处,原文网址:http://blog.csdn.net/m_changgong/article/details/8284135 作者:张燕广

实现的功能:1)演示使用sqlite3持久化数据。

关键词:数据持久化 sqlite3 数据库

1、将上一篇iPhone开发【二十二】数据持久化总结之第3篇归档(NSKeyedArchiver、NSKeyedUnarchiver)的工程拷贝一份,名称修改为Persistence-sqlite,工程结构如下:


Person类已经没用了,可以删掉。

2、为工程添加sqlite3的库libsqlite3.dylib,如下图所示:


3、主要修改了ViewController类,ViewController.h如下:

[cpp] view plaincopy
  1. <span style="font-size:18px;">#define kFileName @"archive"  
  2. #define kDataKey @"Data"  
  3. #define kSqliteFileName @"data.db3"  
  4.   
  5. #import <UIKit/UIKit.h>  
  6.   
  7. @interface ViewController : UIViewController  
  8. @property(nonatomic,retain)IBOutlet UITextField *name;  
  9. @property(nonatomic,retain)IBOutlet UITextField *gender;  
  10. @property(nonatomic,retain)IBOutlet UITextField *age;  
  11. @property(nonatomic,retain)IBOutlet UITextField *education;  
  12.   
  13. -(NSString *)dataFilePath;  
  14. -(void)applicationWillResignActive:(NSNotification *)nofication;  
  15.   
  16. @end</span>  
ViewController.m如下:

[cpp] view plaincopy
  1. <span style="font-size:18px;">#import "ViewController.h"  
  2. #import "Person.h"  
  3. #import <sqlite3.h>  
  4.   
  5. @implementation ViewController  
  6. @synthesize name,gender,age,education;  
  7.   
  8. -(NSString *)dataFilePath{  
  9.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);  
  10.     NSString *documentsDirectory = [paths objectAtIndex:0];  
  11.     //return [documentsDirectory stringByAppendingPathComponent:kFileName];  
  12.     return [documentsDirectory stringByAppendingPathComponent:kSqliteFileName];  
  13. }  
  14.   
  15. - (void)didReceiveMemoryWarning  
  16. {  
  17.     [super didReceiveMemoryWarning];  
  18.     // Release any cached data, images, etc that aren't in use.  
  19. }  
  20.   
  21. #pragma mark - View lifecycle  
  22.   
  23. - (void)viewDidLoad  
  24. {  
  25.     // Do any additional setup after loading the view, typically from a nib.  
  26.     NSString *filePath = [self dataFilePath];  
  27.     NSLog(@"filePath=%@",filePath);  
  28.       
  29.     if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){  
  30.         //属性列表  
  31.         /* 
  32.         NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath]; 
  33.         name.text = [array objectAtIndex:0]; 
  34.         gender.text = [array objectAtIndex:1]; 
  35.         age.text = [array objectAtIndex:2]; 
  36.         education.text = [array objectAtIndex:3]; 
  37.          
  38.         [array release];*/  
  39.           
  40.         //归档  
  41.         /* 
  42.         NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[self dataFilePath]]; 
  43.         NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data]; 
  44.         Person *person = [unarchiver decodeObjectForKey:kDataKey]; 
  45.         [unarchiver finishDecoding]; 
  46.          
  47.         name.text = person.name; 
  48.         gender.text = person.gender; 
  49.         age.text = person.age; 
  50.         education.text = person.education; 
  51.          
  52.         [unarchiver release]; 
  53.         [data release];*/  
  54.           
  55.         //sqlite3  
  56.         sqlite3 *database;  
  57.         //打开数据库  
  58.         if(sqlite3_open([filePath UTF8String], &database)!=SQLITE_OK){//备注1  
  59.             //数据库打开失败,关闭数据库  
  60.             sqlite3_close(database);  
  61.             NSAssert(0,@"打开数据库失败");  
  62.         }  
  63.           
  64.         char* errorMsg;  
  65.         NSString *createSQL = @"CREATE TABLE IF NOT EXISTS PERSON (name TEXT PRIMARY KEY,gender TEXT,age TEXT,education TEXT);";  
  66.         //创建表  
  67.         if(sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg)!=SQLITE_OK){//备注2  
  68.             //创建表失败,关闭数据库  
  69.             sqlite3_close(database);  
  70.             NSAssert1(0, @"创建表失败:%s", errorMsg);  
  71.         }  
  72.           
  73.         //查询表  
  74.         NSString *querySQL = @"SELECT name,gender,age,education FROM PERSON ORDER BY name";  
  75.   
  76.         //执行查询,遍历查询结果  
  77.         sqlite3_stmt *statment;  
  78.         if(sqlite3_prepare_v2(database, [querySQL UTF8String], -1, &statment, nil) == SQLITE_OK){//备注3  
  79.             //查询成功,执行遍历操作  
  80.             while(sqlite3_step(statment) == SQLITE_ROW){//备注4  
  81.                 const char* pName = (char*)sqlite3_column_text(statment, 0);//备注5  
  82.                 if(pName!=NULL){  
  83.                     self.name.text = [[NSString alloc]initWithUTF8String:pName];  
  84.                 }  
  85.                   
  86.                 char* pGender = (char*)sqlite3_column_text(statment, 1);  
  87.                 if(pGender!=NULL){  
  88.                     self.gender.text = [[NSString alloc]initWithUTF8String:pGender];  
  89.                 }  
  90.                   
  91.                 char* pAge = (char*)sqlite3_column_text(statment, 2);  
  92.                 if(pAge!=NULL){  
  93.                     self.age.text = [[NSString alloc]initWithUTF8String:pAge];  
  94.                 }  
  95.                   
  96.                 char* pEducation = (char*)sqlite3_column_text(statment, 3);  
  97.                 if(pEducation!=NULL){  
  98.                    self.education.text = [[NSString alloc]initWithUTF8String:pEducation];   
  99.                 }  
  100.             }  
  101.             sqlite3_finalize(statment);//备注6  
  102.         }  
  103.         //关闭数据库  
  104.         sqlite3_close(database);//备注7  
  105.     }  
  106.       
  107.     UIApplication *app = [UIApplication sharedApplication];  
  108.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];  
  109.       
  110.     [super viewDidLoad];  
  111. }  
  112.   
  113. -(void)applicationWillResignActive:(NSNotification *)nofication{  
  114.       
  115.     //属性列表  
  116.     /* 
  117.     NSMutableArray *array = [[NSMutableArray alloc]init]; 
  118.     [array addObject:name.text]; 
  119.     [array addObject:gender.text]; 
  120.     [array addObject:age.text]; 
  121.     [array addObject:education.text]; 
  122.     [array writeToFile:[self dataFilePath] atomically:YES]; 
  123.     [array release];*/  
  124.       
  125.     //归档  
  126.     /* 
  127.     Person *person = [[Person alloc]init]; 
  128.     person.name = name.text; 
  129.     person.gender = gender.text; 
  130.     person.age = age.text; 
  131.     person.education = education.text; 
  132.      
  133.     NSMutableData *data = [[NSMutableData alloc]init]; 
  134.     NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data]; 
  135.     [archiver encodeObject:person forKey:kDataKey]; 
  136.     [archiver finishEncoding]; 
  137.      
  138.     [data writeToFile:[self dataFilePath] atomically:YES]; 
  139.     [person release]; 
  140.     [archiver release]; 
  141.     [data release];*/  
  142.       
  143.     //sqlite3  
  144.     sqlite3 *database;  
  145.     //打开数据库  
  146.     if(sqlite3_open([[self dataFilePath] UTF8String], &database)!=SQLITE_OK){  
  147.         //数据库打开失败,关闭数据库  
  148.         sqlite3_close(database);  
  149.         NSAssert(0,@"打开数据库失败");  
  150.     }  
  151.       
  152.     char* errorMsg;  
  153.     NSString *updateSQL = @"INSERT OR REPLACE INTO PERSON(name,gender,age,education) VALUES(?,?,?,?);";  
  154.     //执行插入或更新操作  
  155.     sqlite3_stmt *statment;  
  156.     if(sqlite3_prepare_v2(database, [updateSQL UTF8String], -1, &statment, nil) == SQLITE_OK){  
  157.         //绑定变量  
  158.         sqlite3_bind_text(statment, 1, [self.name.text UTF8String], -1, NULL);//备注8  
  159.         sqlite3_bind_text(statment, 2, [self.gender.text UTF8String], -1, NULL);  
  160.         sqlite3_bind_text(statment, 3, [self.age.text UTF8String], -1, NULL);  
  161.         sqlite3_bind_text(statment, 4, [self.education.text UTF8String], -1, NULL);  
  162.     }  
  163.     if(sqlite3_step(statment)!=SQLITE_DONE){  
  164.         NSAssert1(0, @"更新表失败:%s", errorMsg);  
  165.     }  
  166.     sqlite3_finalize(statment);  
  167.     //关闭数据库  
  168.     sqlite3_close(database);  
  169. }  
  170.   
  171. - (void)viewDidUnload  
  172. {  
  173.     [super viewDidUnload];  
  174.     // Release any retained subviews of the main view.  
  175.     // e.g. self.myOutlet = nil;  
  176.     self.name = nil;  
  177.     self.gender = nil;  
  178.     self.age = nil;  
  179.     self.education = nil;  
  180. }  
  181.   
  182. -(void)dealloc{  
  183.     [name release];  
  184.     [gender release];  
  185.     [age release];  
  186.     [education release];  
  187. }  
  188.   
  189. - (void)viewWillAppear:(BOOL)animated  
  190. {  
  191.     [super viewWillAppear:animated];  
  192. }  
  193.   
  194. - (void)viewDidAppear:(BOOL)animated  
  195. {  
  196.     [super viewDidAppear:animated];  
  197. }  
  198.   
  199. - (void)viewWillDisappear:(BOOL)animated  
  200. {  
  201.     [super viewWillDisappear:animated];  
  202. }  
  203.   
  204. - (void)viewDidDisappear:(BOOL)animated  
  205. {  
  206.     [super viewDidDisappear:animated];  
  207. }  
  208.   
  209. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  210. {  
  211.     // Return YES for supported orientations  
  212.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  213. }  
  214.   
  215. @end</span>  
代码解释:

备注1:sqlite3_open():打开数据库

在操作数据库之前,首先要打开数据库。

这个函数打开一个sqlite数据库文件的连接并且返回一个数据库连接对象。

第1个参数:数据文件路径必须用C风格字符串(不能用NSString),[filePath UTF8String]将filePath转换为C风格字符串。

第2个参数:是返回的数据库连接对象。

备注2sqlite3_exec():执行SQL语句
      第1个参数:数据库指针,是前面open函数得到的指针
      第2个参数:const char *sql是一条sql 语句,以\0结尾。
      第3个参数:sqlite3_callback 是回调,当这条语句执行之后,sqlite3会调用这个回调函数。
      第4个参数:void*是一个指针,可以传递任何一个指针参数到这里,这个参数最终会传到回调函数里面,如果不需要传递指针给回调函数,可以填NULL
备注3:sqlite3_prepare_v2():将sql文本转换成一个准备语句(prepared statement)对象,同时返回这个对象的指针
     第1个参数:数据库指针,是前面open函数得到的指针
     第2个参数:sql语句,必须是C风格字符串
     第3个参数:如果该参数小于0,则函数取出zSql中从开始到第一个0终止符的内容;如果nByte不是负的,那么它就是这个函数能从zSql中读取的字节数的最大值。如果nBytes非负,zSql在第一次遇见’/000/或’u000’的时候终止
    第4个参数:上面提到zSql在遇见终止符或者是达到设定的nByte之后结束,假如zSql还有剩余的内容,那么这些剩余的内容被存放到pZTail中,不包括终止符
备注4:sqlite3_step()
    这个过程用于执行有前面sqlite3_prepare创建的准备语句。这个语句执行到结果的第一行可用的位置。继续前进到结果的第二行的话,只需再次调用sqlite3_setp()。继续调用sqlite3_setp()直到这个语句完成,那些不返回结果的语句(如:INSERT,UPDATE,或DELETE),sqlite3_step()只执行一次就返回
备注5:sqlite3_column_text()
    从结果集中获取各列的值,需要注意的是:第一列的索引是0。
备注6:
sqlite3_finalize()

这个过程销毁前面被sqlite3_prepare创建的准备语句,每个准备语句都必须使用这个函数去销毁以防止内存泄露。

在空指针上调用这个函数没有什么影响,同时可以在准备语句的生命周期的任一时刻调用这个函数:在语句被执行前,一次或多次调用

sqlite_reset之后,或者在sqlite3_step任何调用之后。

备注7:sqlite3_close()

          关闭前面使用sqlite3_open打开的数据库连接,任何与这个连接相关的准备语句必须在调用这个关闭函数之前被释放掉。

备注8:sqlite3_bind_text()

第1个参数:指向在sqlite3_prepare_v2()调用中使用的sqlite3_stme。

第2个参数:所绑定的变量的索引(sql语句中第一个问号的索引),需要注意的是:第一个问号的索引是1,而不是0。

第3个参数:只有少数绑定函数,比如用于绑定文本或二进制数据的绑定函数,这个参数用来设定传递数据的长度。对于C字符串,可以传递-1来代替字符串的长度,意思是要是要使用整个字符串。

第4个参数:回调函数,一般用于在语句执行后做内存清理相关的工作。可以设置为NULL。

4、数据库文件的保存位置是: /Users/duobianxing/Library/Application Support/iPhone Simulator/5.0/Applications/CC47C118-7FE7-4718-A4AA-635FBCC36AED/Documents/data.db3

原创粉丝点击