Simple use of Sqlite in IOS apps

Source: Internet
Author: User

IOS appAboutSqliteUsage is what we will introduce in this article,SqliteIs embedded and lightweight SQLDatabase.SqliteIs implemented by c. It is widely used in most browsers that support html5, except ie), IOS, android, and small web application systems that are portable.

Preparation before using sqlite

UseSqliteYesIos appThe first time I faced c in development, including me. Because sqlite is written in c, objc can directly use c code. Before sqlite, the cocoa touch framework is generally used, which is based on objc.

First, add the following to the header file of the corresponding file:

 
 
  1. #import "/usr/include/sqlite3.h" 

Add the required database to Frameworks. Otherwise, an error is returned:

 
 
  1. Undefined symbols:   
  2.   "_sqlite3_open", referenced from: 

The method for adding data to the database is:

Select sqlite Library:

Effect:

Then, there should be a member variable, such as my code:

 
 
  1. @interface DetailViewController : UIViewController <UIPopoverControllerDelegate, UISplitViewControllerDelegate> {   
  2.     UIPopoverController *popoverController;   
  3.     UIToolbar *toolbar;   
  4.     id detailItem;   
  5.     UILabel *detailDescriptionLabel;   
  6.     sqlite3 *database; 

Open Database

Sqlite databases are file databases and stored in file systems. Therefore, you need to know where the file is saved. For more information, see operations on the file in the iOS app. For example, save this article to the Documents directory. Code:

 
 
  1. NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory   
  2.                                                    , NSUserDomainMask   
  3.                                                    , YES);   
  4. NSString *databaseFilePath=[[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"mydb"];   
  5.  
  6. if (sqlite3_open([databaseFilePath UTF8String], &database)==SQLITE_OK) {   
  7.     NSLog(@"open sqlite db ok.");   

View the Documents directory through ssh and find that the mydb file has been created. The sqlite policy is to open the file if it exists, and create a file if it does not exist, that is, to create a database.

Note that the c syntax is used, and sqlite3_open refers to the database address.

Close Database

When the database is used up, close it, for example, when exiting the application:

 
 
  1. - (void)viewDidUnload {   
  2.     // Release any retained subviews of the main view.   
  3.     // e.g. self.myOutlet = nil;   
  4.    sqlite3_close(database);   
  5.     self.popoverController = nil;   

Table creation statement

If no table exists after the database is opened, create the table:

 
 
  1. char *errorMsg;   
  2. const char *createSql="create table if not exists persons (id integer primary key autoincrement,name text)";   
  3.  
  4. if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) {   
  5.     NSLog(@"create ok.");   

Note that errorMsg transmits the address, because this function uses address reference to write error characters.

Insert records to a table

Similar to the table creation statement:

 
 
  1. Const char * insertSql = "insert into persons (name) values ('zhang san ')";
  2. If (sqlite3_exec (database, insertSql, NULL, NULL, & errorMsg) = SQLITE_ OK ){
  3. NSLog (@ "insert OK .");
  4. }

Handle error messages

If you use errorMsg in multiple places, you need to clear the string after each use, for example:

 
 
  1. if (sqlite3_exec(database, createSql, NULL, NULL, &errorMsg)==SQLITE_OK) {   
  2.     NSLog(@"create ok.");   
  3. }else {   
  4.     NSLog(@"error: %s",errorMsg);   
  5.     sqlite3_free(errorMsg);   

Query Result set

Statement is required for query of result sets:

 
 
  1. const char *selectSql="select id,name from persons";   
  2. sqlite3_stmt *statement;   
  3. if (sqlite3_prepare_v2(database, selectSql, -1, &statement, nil)==SQLITE_OK) {   
  4.     NSLog(@"select ok.");   
  5. }   
  6.  
  7. while (sqlite3_step(statement)==SQLITE_ROW) {   
  8.     int _id=sqlite3_column_int(statement, 0);   
  9.     char *name=(char *)sqlite3_column_text(statement, 1);   
  10.     NSLog(@"row>>id %i, name %s",_id,name);   
  11. }   
  12.  
  13. sqlite3_finalize(statement); 

But there is a problem here, look at the printed log:

Garbled. Because the char type is used directly.

The solution is to replace char with nsstring:

 
 
  1. while (sqlite3_step(statement)==SQLITE_ROW) {   
  2.     int _id=sqlite3_column_int(statement, 0);   
  3.     NSString *name=[[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];   
  4.     NSLog(@"row>>id %i, name %@",_id,name);   

Char performs an explicit encoding when nsstring is generated. Solution:

Note:

WriteDatabase, There is no problem using char, writeDatabaseThe encoding is correct;

Extracted from the database. ascii decoding may be used by default, resulting in garbled characters.

Summary:IOS appAboutSqliteI hope this article will be helpful to 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.