Database usage tutorial in iPhone Development

Source: Internet
Author: User
Tags sqlite manager

IPhoneUnder developmentDatabaseUsage is what we will introduce in this article,IPhoneSqlite is used.DatabaseI used the firefox plug-in Sqlite Manager to manage sqlite. This plug-in is very useful and allows you to easily create and manage sqlite in a view. If you don't talk nonsense, go to the topic.

To use sqlite, first introduce the libsqlite3.0.dylib file in Frameworks. I skipped the steps and then createdDatabase.DatabaseAdd to the Resources directory (remember to check the Copy items into... option). Now the preparation is complete. Write the code below.

For ease of use and future maintenance, I have created a class here to encapsulate the database-related code. Create an NSObject class named GADatabase here and add the following code to the implementation file:

 
 
  1. #import <sqlite3.h> 
  2.  
  3. id getColValue(sqlite3_stmt *stmt,int iCol) {  
  4.     int type = sqlite3_column_type(stmt, iCol);  
  5.     switch (type) {  
  6.         case SQLITE_INTEGER:  
  7.             return [NSNumber numberWithInt:sqlite3_column_int(stmt, iCol)];  
  8.             break;  
  9.         case SQLITE_FLOAT:  
  10.             return [NSNumber numberWithDouble:sqlite3_column_double(stmt, iCol)];  
  11.             break;  
  12.         case SQLITE_TEXT:  
  13.             return [NSString stringWithUTF8String:sqlite3_column_text(stmt, iCol)];  
  14.             break;  
  15.         case SQLITE_BLOB:  
  16.             return [NSData dataWithBytes:sqlite3_column_blob(stmt, iCol) length:sqlite3_column_bytes(stmt, iCol)];  
  17.             break;  
  18.         case SQLITE_NULL:  
  19.             return @"";  
  20.             break;  
  21.         default:  
  22.             return @"NONE";  
  23.             break;  
  24.     }  

Here, I use the C-style definition and the definition is out of @ implementation for ease of use. With this function, it will be very convenient for data extraction in the future, the data type can be increased or decreased according to the actual situation. OK. Now Add the following code between @ implementation and @ end to get the sqlite address in the iphone:

 
 
  1. + (NSString *)pathForDatabase {  
  2.     NSArray *arrayOfPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  3.     NSString *path = [arrayOfPaths objectAtIndex:0];  
  4.     path = [path stringByAppendingPathComponent:@"yourDatabaseName.sqlite"];  
  5.     NSLog(path);  
  6.     NSFileManager *fileManager = [NSFileManager defaultManager];  
  7.     if(![fileManager fileExistsAtPath:path]){  
  8.         NSString *databaseSource = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"yourDatabaseName.sqlite"];  
  9.         if(![fileManager copyItemAtPath:databaseSource toPath:path error:nil]){  
  10.             return nil;  
  11.         }  
  12.     }  
  13.     return path;  

Now you can write SQL statements. Here are some examples:

Query a field:

 
 
  1. - (NSString *)select:(NSString *)Parameter {  
  2.     sqlite3 *database;  
  3.     sqlite3_stmt *stm;  
  4.     NSString *result = [NSString string];  
  5.     NSString *sql = [NSString stringWithFormat:@"SELECT columnName FROM table WHERE columnName='%@'", Parameter];  
  6.      
  7.     if(sqlite3_open([[GADatabase pathForDatabase] UTF8String], &database) == SQLITE_OK) {  
  8.         if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stm, NULL) == SQLITE_OK) {  
  9.             if(sqlite3_step(stm) == SQLITE_ROW) {  
  10.                 result = getColValue(stm, 0);  
  11.             }  
  12.         }  
  13.         sqlite3_finalize(stm);  
  14.     }  
  15.     sqlite3_close(database);  
  16.     return result;  

To query multiple fields, you can use an array and a custom class to store them. For example:

 
 
  1. - (NSMutableArray *)selectUsers {  
  2.     sqlite3 *database;  
  3.     sqlite3_stmt *stm;  
  4.     NSMutableArray *result = [[NSMutableArray alloc] init];  
  5.     NSString *sql = @"SELECT * FROM users";  
  6.      
  7.     if(sqlite3_open([[GADatabase pathForDatabase] UTF8String], &database) == SQLITE_OK) {  
  8.         if(sqlite3_prepare_v2(database, [sql UTF8String], -1, &stm, NULL) == SQLITE_OK) {  
  9.             while(sqlite3_step(stm) == SQLITE_ROW) {  
  10.                 GAData *userObj = [[GAData alloc] init];  
  11.                 userObj.rId = getColValue(stm, 0);  
  12.                 userObj.userName = getColValue(stm, 1);  
  13.                 userObj.passWord = getColValue(stm, 2);  
  14.                 [result addObject:userObj];  
  15.                 [userObj release];  
  16.             }  
  17.         }  
  18.         sqlite3_finalize(stm);  
  19.     }  
  20.     sqlite3_close(database);  
  21.     return result;     

The GAData class is defined as follows:

 
 
  1. #import <Foundation/Foundation.h> 
  2. @interface GAData : NSObject {  
  3.     NSNumber *rId;  
  4.     NSString *userName;  
  5.     NSString *passWord;  
  6. }  
  7. @property(nonatomic, retain)NSNumber *rId;  
  8. @property(nonatomic, retain)NSString *userName;  
  9. @property(nonatomic, retain)NSString *passWord;  
  10. @end  
  11. #import "GAData.h"  
  12. @implementation GAData  
  13. @synthesize rId;  
  14. @synthesize userName;  
  15. @synthesize passWord;  
  16. @end 

Add data to the database:

 
 
  1. - (void)addUser:(GAData *)addUserObj {  
  2.     sqlite3 *database;  
  3.     NSString *sql = [NSString stringWithFormat:@"INSERT INTO users (userName, passWord) VALUES('%@','%@')",  
  4.                      addUserObj.userName, addUserObj.passWord];  
  5.      
  6.     int status = sqlite3_open([[GADatabase pathForDatabase] UTF8String], &database);  
  7.     if(status != SQLITE_OK) {  
  8.         return;  
  9.     }  
  10.     status = sqlite3_exec(database, [sql UTF8String], 0, 0, NULL);  
  11.     if(status != SQLITE_OK) {  
  12.         return;  
  13.     }  
  14.     sqlite3_close(database);  

Deletion and modification are similar to addition. They are nothing more than SQL statements, so they are no longer used as an example. Let's talk about the time function in sqlite, so far, I have only used functions about the number of days of computing, so I will not introduce them. You can search for them online and see the following SQL statement:

 
 
  1. SELECT columnName FROM table WHERE (julianday(date(columnName))-julianday(date('now')))>10 

This function returns the number of days, starting from January 1, November 24, 4714 BC, Greenwich Mean Time. The date () function returns a date in YYYY-MM-DD format. Therefore, the above statement is not difficult to understand.

AboutDatabaseI have written so much about it for the time being. If there are some bad or wrong places, you are welcome to point it out. Let's learn it together. Finally, I would like to remind you that if you modifyDatabaseContent, You need to delete the previously compiled program, re-compile, or find the path when the program is running, deleteDatabaseFile, and then re-compile and run, only in this way, in your programDatabaseWill be updated, remember!

Summary:IPhoneUnder developmentDatabaseI hope this article will help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.