IOS Database Persistence

Source: Internet
Author: User
Tags sql error sqlite db

Java code

    1. -(void)  addobserver{  
    2.     //Perform actions when the program enters the background    
    3.     UIApplication *app = [UIApplication  sharedapplication];  
    4.     [[ NSNotificationCenter  defaultcenter] addobserver: self  
    5.                                                  selector: @selector (appwillresignactive)  name:uiapplicationwillresignactivenotification  object:app];  
    6. }  
    7. -(void)  appwillresignActive{  
    8.     nslog (@ "listening test");   
    9. }  

-(void) addobserver{

Perform actions when the program enters the background

UIApplication *app = [UIApplication sharedapplication];

[[Nsnotificationcenter Defaultcenter] Addobserver:self

Selector: @selector (appwillresignactive) name:uiapplicationwillresignactivenotification Object:app];

}

-(void) appwillresignactive{

NSLog (@ "Monitoring test");

}

Head 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 you use errormsg in more than one place, clear the string each time you use it, such as this:
  20. NSLog (@ "error:%s", errormsg);
  21. Sqlite3_free (ERRORMSG);
  22. }
  23. Inserting records into a table
  24. const char *insertsql= "INSERT into persons (name) values (\" Zhang San \ ")";
  25. if (sqlite3_exec (database, insertsql, NULL, NULL, &ERRORMSG) ==SQLITE_OK)
  26. {
  27. NSLog (@ "insert OK.");
  28. }else
  29. {
  30. If you use errormsg in more than one place, clear the string each time you use it, such as this:
  31. NSLog (@ "error:%s", errormsg);
  32. Sqlite3_free (ERRORMSG);
  33. }
  34. The query for the result set needs to be statement:
  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 you use errormsg in more than one place, clear the string each time you use it, such as this:

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

Sqlite3_free (ERRORMSG);

}

Inserting records into a table

const char *insertsql= "INSERT into persons (name) values (\" Zhang San \ ")";

if (sqlite3_exec (database, insertsql, NULL, NULL, &ERRORMSG) ==SQLITE_OK)

{

NSLog (@ "insert OK.");

}else

{

If you use errormsg in more than one place, clear the string each time you use it, such as this:

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

Sqlite3_free (ERRORMSG);

}

The query for the result set needs to be statement:

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 Table action

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);

Inserting data

Sqlite3_exec (db, "insert into T (id,msg) VALUES (1, ' Ady Liu ')", null,null,&errmsg);

Pre-compilation operations

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 cumbersome and the process of complete precompilation is:
Create a Sqlite3_stmt object from SQLITE3_PREPARE_V2 ()
To bind a precompiled field's value by Sqlite3_bind_* ()
Execute SQL statements with Sqlite3_step ()
Reset precompiled statements with Sqlite3_reset (), repeat operations 2 times
Destroying resources through Sqlite3_finalize ()

Precompiled SQL statements can contain several forms:
?
? NNN
: VVV
@VVV
$VVV
NNN represents a number, and VVV represents a string.

What if it is? or? NNN, you can operate directly sqlite3_bind_* (), and if it is a string, you also need to get the corresponding index by Sqlite3_bind_parameter_index () and then call the sqlite3_bind_* () operation. This is typically used to construct an indeterminate condition for an SQL statement (Dynamic SQL statement).

Query operations

Wrote

The explanation of the callback function refers to the top description. First, 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 define the callback function, 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 that do not use callbacks

Wrote

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 records affected

We can use the API of Sqlite3_change (SQLITE3 *) 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));

}

Summarize

Wrote

Here we touch the 13 APIs of SQLITE3:
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 ()
In fact, as of SQLITE3.7.14 (2012/09/03), a total of 204 API functions (http://www.sqlite.org/c3ref/funclist.html) were provided.
But there are about 6 of the most streamlined API functions:
Sqlite3_open ()
Sqlite3_prepare ()
Sqlite3_step ()
Sqlite3_column ()
Sqlite3_finalize ()
Sqlite3_close ()
There are 10 core APIs (4 additions on the Thin API):
Sqlite3_exec ()
Sqlite3_get_table ()
Sqlite3_reset ()
Sqlite3_bind ()
So it's easier to get it in the hands.

IOS Database Persistence

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.