IOS database persistence, ios Database

Source: Internet
Author: User
Tags sql error sqlite db

IOS database persistence, ios Database

Java code

  1. -(Void) addObserver {
  2. // Perform the operation when the program enters the background
  3. UIApplication * app = [UIApplication sharedApplication];
  4. [[Nsicationcenter center defacenter center] addObserver: self
  5. Selector: @ selector (appwillresignActive) name: UIApplicationWillResignActiveNotification object: app];
  6. }
  7. -(Void) appwillresignActive {
  8. NSLog (@ "listener test ");
  9. }

-(Void) addObserver {

// Perform the operation when the program enters the background

UIApplication * app = [UIApplication sharedApplication];

[[Nsicationcenter center defacenter center] addObserver: self

Selector: @ selector (appwillresignActive) name: UIApplicationWillResignActiveNotification object: app];

}

-(Void) appwillresignActive {

NSLog (@ "listener test ");

}

Header Introduction

Java code

  1. # Import "sqlite3.h"

# Import "sqlite3.h"

 

Java code

  1. -(Void) makeDBinfo {
  2. NSArray * documentsPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );
  3. NSString * databaseFilePath = [[documentsPaths objectAtIndex: 0] stringByAppendingPathComponent: @ "mydb"];
  4. Char * errorMsg;
  5. // Open or create a database
  6. Sqlite3 * database;
  7. If (sqlite3_open ([databaseFilePath UTF8String], & database )! = SQLITE_ OK ){
  8. Sqlite3_close (database );
  9. } Else {
  10. NSLog (@ "open sqlite db OK .");
  11. }
  12. // Create a database table
  13. Const char * createSql = "create table if not exists persons (id integer primary key autoincrement, name text )";
  14. If (sqlite3_exec (database, createSql, NULL, NULL, & errorMsg) = SQLITE_ OK)
  15. {
  16. NSLog (@ "create table OK .");
  17. } Else
  18. {
  19. // If errorMsg is used in multiple places, clear the string after each use, for example:
  20. NSLog (@ "error: % s", errorMsg );
  21. Sqlite3_free (errorMsg );
  22. }
  23. // Insert records into the table
  24. Const char * insertSql = "insert into persons (name) values (\" James \")";
  25. If (sqlite3_exec (database, insertSql, NULL, NULL, & errorMsg) = SQLITE_ OK)
  26. {
  27. NSLog (@ "insert OK .");
  28. } Else
  29. {
  30. // If errorMsg is used in multiple places, clear the string after each use, for example:
  31. NSLog (@ "error: % s", errorMsg );
  32. Sqlite3_free (errorMsg );
  33. }
  34. // Statement is required for query of result sets:
  35. Const char * selectSql = "select id, name from persons where name =? ";
  36. Sqlite3_stmt * statement;
  37. If (sqlite3_prepare_v2 (database, selectSql,-1, & statement, nil) = SQLITE_ OK ){
  38. NSLog (@ "select OK .");
  39. Sqlite3_bind_text (statement, 1, "Zhang San",-1, NULL );
  40. While (sqlite3_step (statement) = SQLITE_ROW ){
  41. Int _ id = sqlite3_column_int (statement, 0 );
  42. NSString * name = [[NSString alloc] initWithCString :( char *) sqlite3_column_text (statement, 1) encoding: NSUTF8StringEncoding];
  43. NSLog (@ "row> id % I, name % @", _ id, name );
  44. }
  45. Sqlite3_finalize (statement );
  46. }
  47. Sqlite3_close (database );
  48. }

-(Void) makeDBinfo {

NSArray * documentsPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES );

NSString * databaseFilePath = [[documentsPaths objectAtIndex: 0] stringByAppendingPathComponent: @ "mydb"];

Char * errorMsg;

// Open or create a database

Sqlite3 * database;

If (sqlite3_open ([databaseFilePath UTF8String], & database )! = SQLITE_ OK ){

Sqlite3_close (database );

} Else {

NSLog (@ "open sqlite db OK .");

}

// Create a database table

Const char * createSql = "create table if not exists persons (id integer primary key autoincrement, name text )";

If (sqlite3_exec (database, createSql, NULL, NULL, & errorMsg) = SQLITE_ OK)

{

NSLog (@ "create table OK .");

} Else

{

// If errorMsg is used in multiple places, clear the string after each use, for example:

NSLog (@ "error: % s", errorMsg );

Sqlite3_free (errorMsg );

}

// Insert records into the table

Const char * insertSql = "insert into persons (name) values (\" James \")";

If (sqlite3_exec (database, insertSql, NULL, NULL, & errorMsg) = SQLITE_ OK)

{

NSLog (@ "insert OK .");

} Else

{

// If errorMsg is used in multiple places, clear the string after each use, for example:

NSLog (@ "error: % s", errorMsg );

Sqlite3_free (errorMsg );

}

// Statement is required for query of result sets:

Const char * selectSql = "select id, name from persons where name =? ";

Sqlite3_stmt * statement;

If (sqlite3_prepare_v2 (database, selectSql,-1, & statement, nil) = SQLITE_ OK ){

NSLog (@ "select OK .");

Sqlite3_bind_text (statement, 1, "Zhang San",-1, NULL );

While (sqlite3_step (statement) = SQLITE_ROW ){

Int _ id = sqlite3_column_int (statement, 0 );

NSString * name = [[NSString alloc] initWithCString :( char *) sqlite3_column_text (statement, 1) encoding: NSUTF8StringEncoding];

NSLog (@ "row> id % I, name % @", _ id, name );

}

Sqlite3_finalize (statement );

}

Sqlite3_close (database );

 

}

 

Delete a table

 

Constchar * SQL _drop_table = "drop table if exists t ";

Constchar * SQL _create_table = "create table t (id int primary key, msg varchar (128 ))";

 

Sqlite3_exec (db, SQL _drop_table, 0, 0, & errmsg );

Sqlite3_exec (db, SQL _create_table, 0, 0, & errmsg );

 

Insert data

Sqlite3_exec (db, "insert into t (id, msg) values (1, 'ady liu')", NULL, NULL, & errmsg );

 

 

Pre-compile operation

Int I = 0;

Sqlite3_stmt * stmt;

Char ca [255];

 

// Prepare statement

Sqlite3_prepare_v2 (db, "insert into t (id, msg) values (?,?) ",-1, & stmt, 0 );

For (I = 10; I <20; I ++ ){

Sprintf (ca, "HELLO # % I", I );

Sqlite3_bind_int (stmt, 1, I );

Sqlite3_bind_text (stmt, 2, ca, strlen (ca), NULL );

Sqlite3_step (stmt );

Sqlite3_reset (stmt );

}

Sqlite3_finalize (stmt)

The pre-compilation operation is troublesome. The complete pre-compilation process is as follows:
Create a sqlite3_stmt object through sqlite3_prepare_v2 ()
Bind the pre-compiled field value through sqlite3_bind _ * ()
Use sqlite3_step () to execute an SQL statement
Use sqlite3_reset () to reset the pre-compiled statement. Repeat the operation twice.
Use sqlite3_finalize () to destroy resources

 

Pre-compiled SQL statements can contain the following forms:
?
? NNN
: VVV
@ VVV
$ VVV
NNN indicates a number, and VVV indicates a string.

 

If yes? Or? NNN, you can directly perform sqlite3_bind _ * (). If it is a string, you also need to obtain the corresponding index through sqlite3_bind_parameter_index () and then call sqlite3_bind. This is usually used to construct SQL statements with indefinite conditions (dynamic SQL statements ).

 

Query operations

Write

For more information about callback functions, see the preceding description. Declare a callback function.
Int print_record (void *, int, char **, char **);

Query code
// Select data
Ret = sqlite3_exec (db, "select * from t", print_record, NULL, & errmsg );
If (ret! = SQLITE_ OK ){
Fprintf (stderr, "query SQL error: % s \ n", errmsg );
}


Now we define the callback function, which is just a simple output field value.
Int print_record (void * params, int n_column, char ** column_value, char ** column_name ){
Int I;
For (I = 0; I <n_column; I ++ ){
Printf ("\ t % s", column_value [I]);
}
Printf ("\ n ");
Return 0;
}

 

Query operations without callback

Write

Define the variables used
Char ** dbresult; int j, nrow, ncolumn, index;
Query operations
// Select table
Ret = sqlite3_get_table (db, "select * from t", & dbresult, & nrow, & ncolumn, & errmsg );
If (ret = SQLITE_ OK ){
Printf ("query % I records. \ n", nrow );
Index = ncolumn;
For (I = 0; I <nrow; I ++ ){
Printf ("[% 2i]", I );
For (j = 0; j <ncolumn; j ++ ){
Printf ("% s", dbresult [index]);
Index ++;
}
Printf ("\ n ");
}
}
Sqlite3_free_table (dbresult );

Number of affected records

We can use the sqlite3_change (sqlite3 *) API to count the number of records affected by the last operation.
Ret = sqlite3_exec (db, "delete from t", NULL, NULL, & errmsg );

If (ret = SQLITE_ OK ){

Printf ("delete records: % I \ n", sqlite3_changes (db ));

}

 

Summary

 

Write

Here we have access to 13 SQLITE3 APIs:
Sqlite3_open ()
Sqlite3_exec ()
Sqlite3_close ()
Sqlite3_prepare_v2
Sqlite3_bind _*()
Sqlite3_bind_parameter_index ()
Sqlite3_step ()
Sqlite3_reset ()
Sqlite3_finalize ()
Sqlite3_get_table
Sqlite3_change ()
Sqlite3_free ()
Sqlite3_free_table ()
As of fact SQLITE3.7.14 () has provided a total of 204 API functions (http://www.sqlite.org/c3ref/funclist.html ).
However, there are about 6 streamlined API functions:
Sqlite3_open ()
Sqlite3_prepare ()
Sqlite3_step ()
Sqlite3_column ()
Sqlite3_finalize ()
Sqlite3_close ()
There are also 10 core APIs (four more on the basis of simplified APIs ):
Sqlite3_exec ()
Sqlite3_get_table ()
Sqlite3_reset ()
Sqlite3_bind ()
Therefore, it is easier to master.

 

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.