Introduction of SQLite
SQLite is a pure C implementation, so doomed it is a cross-platform tool, both under the Android and iOS can be used, but also can write common code, convenient for us to transplant. Of course, Android and iOS have encapsulated SQLite for developers to use, but this is not easy to transplant, the other is the efficiency of the package after how we do not know, so or the original ecological health. The last important reason is that the use of native is also quite simple. I'll explain it to you in the next tutorial one by one.
First of all, the most important thing is to import SQLite in the project, the Apple SDK has been included in you, so just import a call libsqlite3.0.dylib framework. Then, include the corresponding header file: #import "Sqlite3.h".
The introduction to the iOS project is over and you can use it normally.
In other projects, such as Android, Embedded Linux, we need to add two files, please go to http://sqlite.org/download.html download the corresponding file, you use which platform on the corresponding file, but I usually the first one called Sqlite-amalgamation-3071000.zip's file, which contains a sqlite3.c and a sqlite3.h. I'll just drag the two files to my project and include the. h file in the area where I need to use it. This is better than invoking a compiled library, I can debug more conveniently, I can make some changes to his features, such as I could add a set of my own encryption, or I can add a few callback functions to facilitate interaction with the upper layer. Or remove the functionality we don't need, and reduce the code redundancy.
In my next tutorial, I will use pure C to explain, although I will be in Apple's Xcode environment to write code, but in addition to the library is not the same as the reference, the other is the same, I will try to avoid the platform-related things. Of course, sometimes I may write a UI demo, this time it is inevitable to deal with the platform, but the key point of this tutorial is to understand the underlying principles, learn to SQLite API calls, according to their own needs to encapsulate and provide interface.
Finally, attach Xcode to import SQLite in the diagram:
Click the plus sign. Then search for sqlite3, select Sqlite3.0.dylib, and then click Add. Then you see the Library guide in the project.
Then import the header file where you want to call:
Data type of SQLite
to use a database you have to figure out his data type first, don't you? SQLite data types and their simplicity:
- Null. Null value
- INTEGER. Integral type
- Real. Floating-point type
- Text. Literal type
- Blob. Binary type, used to store files, such as pictures.
These are the storage types for SQLite, of course, each type will have different subtypes depending on the length of the data. This does not speak now because you can use these large types directly. You know what kind of a few. Later in the actual use of slowly familiar with the good.
SQLite actually does not force you to declare the data type beforehand, it will be automatically converted according to the actual type in the actual stored procedure, but we do not recommend Non-datatype to improve the efficiency.
Here is a list of the code to create a table, mainly let you understand the actual use of data types:
CREATE TABLE Student (
name TEXT, //name
no INTEGER,//School number
Totalscore Real,//total
photo BLOB //Photo
);
Definition of
handle
to manipulate a database you have to have a handle to the database (and you have this difficult word, but there is no better word to replace it). You don't really have to care about the word, you just have to figure out what he is. Just like the shoes why the shoes, carefully think about it is difficult to understand, but clear his function is OK, is not it?
Handle in many places we have seen, the most common is the file handle, we have to manipulate a file, we need to get a file handle. What is a handle? In fact it is very simple, the handle is a description of the east, he is defined as a structure, this structure may contain the specific information to describe the Dongdong, such as location, size, type and so on. We have this descriptive information that we can go to find this stuff and manipulate it.
A word: A handle is a descriptive structure of an object.
Let's take a look at how the SQLite handle is defined (don't be scared, just skip the code):
struct Sqlite3 {Sqlite3_vfs *pvfs; /* OS Interface */int nDb; /* Number of backends currently in-use */Db *adb; * All backends */int flags; * Miscellaneous flags. Below * * unsigned int openflags; * Flags passed to Sqlite3_vfs.xopen () */int errcode; /* Most Recent error code (sqlite_*) */int errmask; /* & result codes with this before returning * * U8 autocommit; /* the AUTO-COMMIT flag. * * U8 Temp_store; /* 1:file 2:memory 0:default * * U8 mallocfailed; /* True If we have seen a malloc failure * * U8 Dfltlockmode; /* Default Locking-mode for attached DBS */signed Char Nextautovac; /* Autovac setting after VACUUM if >=0 * * U8 Suppresserr; /* Do not issue error messages if True * * U8 vtabonconflict; /* Value to return for s3_vtab_on_conflict () */int nextpagesize; /* Pagesize after VACUUM if >0 */int ntable; /* Number of TabLes in the database */COLLSEQ *pdfltcoll; /* The default collating sequence (BINARY) * * i64 Lastrowid; /* ROWID of most recent insert (* above)/U32 magic; /* Magic number for Detect library misuse */int nchange; /* Value returned by sqlite3_changes () */int ntotalchange; /* Value returned by sqlite3_total_changes () * * Sqlite3_mutex *mutex; /* Connection Mutex */int alimit[sqlite_n_limit]; /* Limits/struct Sqlite3initinfo {/* information used during initialization/int iDb; /* When then is being initialized */int newtnum; /* rootpage of table being initialized * * U8 busy; /* TRUE if currently initializing * * U8 Orphantrigger;
/* Last statement is orphaned TEMP trigger/} init; int nextension; /* Number of loaded extensions */void **aextension; /* Array of Shared library handles */struct VDBE *pvdbe; /* List of active virtual machines */int ACtivevdbecnt; /* Number of vdbes currently executing */int writevdbecnt; /* Number of active vdbes that are writing */int vdbeexeccnt; /* Number of nested calls to Vdbeexec () */void (*xtrace) (Void*,const char*); /* Trace function */void *ptracearg; /* Argument to the trace function */void (*xprofile) (Void*,const char*,u64); /* Profiling function */void *pprofilearg; /* Argument to profile function */void *pcommitarg; /* Argument to Xcommitcallback () */int (*xcommitcallback) (void*); /* invoked at every commit. * * void *prollbackarg; /* Argument to Xrollbackcallback () */void (*xrollbackcallback) (void*); /* invoked at every commit.
* * void *pupdatearg;
void (*xupdatecallback) (void*,int, const char*,const char*,sqlite_int64);
#ifndef Sqlite_omit_wal Int (*xwalcallback) (void *, sqlite3 *, const char *, int);
void *pwalarg; #endif void (*xcollneeded) (Void*,sqlite3*,int etextrep,const char*);
void (*XCOLLNEEDED16) (Void*,sqlite3*,int etextrep,const void*);
void *pcollneededarg; Sqlite3_value *perr; /* Most Recent error message */char *zerrmsg; /* Most Recent error message (UTF-8 encoded) */char *zerrmsg16; /* Most Recent error message (UTF-16 encoded)/union {volatile int isinterrupted; * True if Sqlite3_interrupt has been called * * double notUsed1;
/* Spacer/} U1; Lookaside lookaside; /* lookaside malloc Configuration//#ifndef sqlite_omit_authorization int (*xauth) (Void*,int,const char*,const char*,c
Onst char*,const char*); /* Access authorization function */void *pautharg; /* 1st argument to the Access auth function */#endif #ifndef sqlite_omit_progress_callback Int (*xprogress) (void *); /* The progress callback/void *pprogressarg; /* Argument to the progress callback */int nprogressops; /* Number of opcodes for progress callback/#endif #ifndef Sqlite_omiT_virtualtable Hash Amodule; /* Populated by Sqlite3_create_module () * * Vtabctx *pvtabctx; /* Context for Active vtab connect/create * * VTable **avtrans; /* Virtual tables with open transactions */int nvtrans; /* Allocated size of Avtrans * * VTable *pdisconnect; /* Disconnect These in next Sqlite3_prepare () * */#endif Funcdefhash afunc; /* Hash Table of connection functions * * hash acollseq; * All collating sequences * * Busyhandler Busyhandler; /* BUSY callback */int busytimeout; /* Busy handler timeout, in msec * * Db adbstatic[2]; /* Static spaces for the 2 default backends * * SavePoint *psavepoint; /* List of active savepoints */int nsavepoint; /* Number of non-transaction savepoints */int nstatement; /* Number of nested statement-transactions * * U8 istransactionsavepoint; /* True If the outermost savepoint is a TS/i64 ndeferredcons; /* Net deferred constraints this transAction. */int *pnbytesfreed; /* If not NULL, increment this in Dbfree () */#ifdef sqlite_enable_unlock_notify/* The following variables are all P Rotected by the Static_master * * Mutex, not by Sqlite3.mutex.
They are used by the code in NOTIFY.C.
* * * * when x.punlockconnection==y, which means that X are waiting for Y to * unlock so it can proceed. * * * * when x.pblockingconnection==y, which means that something that X tried * * tried to do recently failed with a SQL
ite_locked error due to locks * * held by Y. * * Sqlite3 *pblockingconnection; * Connection that caused sqlite_locked * * Sqlite3 *punlockconnection; /* Connection to watch for unlock */void *punlockarg; /* Argument to Xunlocknotify * */void (*xunlocknotify) (void * *, int); /* Unlock Notify Callback * * Sqlite3 *pnextblocked;
/* Next in the list of all blocked connections * * #endif};
typedef struct SQLITE3 sqlite3;//
is not scared, it does not matter, this code is I posted out to scare you, I did not seriously study the code, and do not want to study, unless the day someone pay a high price to me to study, I now only know how to use the good.
This sqlite3 structure is used to describe the database files in our disk. With this descriptor we can do a variety of operations on this database, the details of the operation we do not need to understand, we need to know how to invoke the API is good, of course, sometimes to understand a little insider, I'll talk about it later.
I used that long word to add a large section of scary code for one purpose: Don't be afraid of the handle.
All right, let's get to the point, SQLite. You have to manipulate the database first we have to create a handle, and then all of the following operations on the database will use this handle.
It is so simple, such a ssqlite handle we have created, we can not be separated from the operation of the database.