Data caching - the use of SQLite relational databases

Use of SQLite relational database

Demo download address

gitOSChina download address


Database (Database): A warehouse for storing data, which stores a table, especially like Excel and Numbers, which store data in the form of tables, and can create multiple tables.

 

Common databases: sqlite, MySQL, SQLServer, Oracle, Access.

The main reason for using a database is that file reading and writing and archiving and reading data need to read all the data at one time, which takes up a lot of memory; the second is the high efficiency of database data, which is reflected in additions, deletions, and changes.

 

Steps to store data in a database

1. Create a new database

2. Create a new table

3. Add multiple fields (column, column, attribute)

4. Add multiple rows of records (row, each row stores the values ​​corresponding to multiple fields)

 

The operation statement of the database (add, delete, modify, check), that is, SQL (Structured Query Language)

SQL statements are not case-sensitive, and strings need to be added with "" or ''

Common syntax: (primary key: is the unique identifier of a piece of data, a table can only have one primary key, and the primary key cannot be repeated. Generally, the primary key name is set to "id", no assignment is required, and it will increase automatically; * represents all field; where is the condition)

1 Table Operation

(1) Create a table: creat table table name (whether the field name field data type is the primary key, the field name field data type, the field name field data type...)

(2) Modify the table name: ALTER TABLE old table name RENAME TO new table name

(3) Delete table: DROP TABLE table name

(4) Add a column to the table: ALTER TABLE table name ADD COLUMN column name data type qualifier

2 Table data manipulation

(1) Check: select field name (or *) from table name where field name = value

(2) Add: insert into table name (field 1, field 2...) values ​​(value 1, value 2...)

(3) Change: update table name set field = value where field = value

(4) Delete: delete from table name where field = value

 

SQLite is a lightweight embedded database that occupies very low resources. In embedded devices, only a few hundred K of memory may be enough. Its processing speed is faster than MySQL, PostgreSQL, two famous databases.

 

SQLite noun explanation

2 important structures

1 sqlite3 *pdb (database handle, similar to file handle FILE)

2 sqlite3_stmt *stmt (this is equivalent to the ODBC Command object, used to save the compiled SQL statement)

5 main functions

1 sqlite3_open() (open database)

2 sqlite3_exec() (execute non-query sql statement)

3 sqlite3_prepare() (when preparing sql statements, executing select statements or using parameterbind, use this function (encapsulating sqlite3_exec))

4 Sqlite3_step() (use this function to move through the recordset after calling sqlite3_prepare)

5 Sqlite3_close() (close the database file)

 

SQLite storage class

1 NULL (value is a NULL value)

2 INTEGER (value is a signed integer stored in 1, 2, 3, 4, 6, or 8 bytes depending on the size of the value)

3 REAL (value is a floating-point value, stored as an 8-byte IEEE floating-point number)

4 TEXT (value is a text string, stored using database encoding (UTF-8, UTF-16BE or UTF-16LE))

5 BLOB (value is a blob of data, stored exactly according to its input)

 

SQLite common statements

1. Open the database sqlite3_open function

2. Preprocessing SQL statement sqlite3_prepare_v2 function

3. Bind parameter sqlite3_bind_text function

4. Execute the SQL statement sqlite3_step function (status: *SQLITE_BUSY-database is locked, *SQLITE_DONE-successful execution process, *SQLITE_ROW-return a row of results, *SQLITE_ERROR-running error, *SQLITE_MISUSE-misuse of this function)

5、提取字段数据sqlite3_column_text、sqlite3_column_blob、sqlite3_column_int等函数

6、释放statement对象资源 sqlite3_finalize函数

7、关闭数据库 sqlite3_close函数

 

SQLite的使用

1、在iOS中使用SQLite时,首先需要添加库文件libsqlite3.tbd


2、导入主头文件 #import<sqlite3.h>


3、数据库操作(注:设置数据库名称及路径)

 

示例代码:

设置数据库路径

- (void)setSQLitePath
{
   if (self.filePath == nil)
    {
       // document目录下
       NSArray *documentArray =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
       NSString *document = [documentArray objectAtIndex:0];
       _filePath = [document stringByAppendingPathComponent:SQLiteFile];
    }
   
    NSLog(@"filePath %@", _filePath);
}


打开数据库,创建表(如果不存在时,才创建数据库并打开

- (void)New
{
   NSString *sql = @"CREATE TABLE IF NOT EXISTS STUDENT(NAME TEXTPRIMARY KEY, ADDRESS TEXT, PHONE TEXT)";
   if (sql && 0 != sql.length)
    {
       [self setSQLitePath];
       
       if (![[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
       {
           // 打开数据库
           sqlite3 *dataBase; // sqlite3
           const char *fileName = [self.filePath UTF8String]; // [xxx UTF8String]是将NSString转换为C字符串,因为SQLite3是采用可移植的C(而不是            Objective-C)编写的,它不知道什么是NSString.
           int openStatus = sqlite3_open(fileName, &dataBase);
           if (openStatus != SQLITE_OK)
           {
                // 数据库打开失败,关闭数据库
                sqlite3_close(dataBase);
               NSAssert(0, @"打开数据库失败");
               
                NSLog(@"打开数据库失败");
           }
        
           NSLog(@"打开数据库成功");
           
           // 创建表
           char *errorMsg;
           const char *execSql = [sql UTF8String];
            int execStatus = sqlite3_exec(dataBase,execSql, NULL, NULL, &errorMsg);
           if (execStatus != SQLITE_OK)
           {
                // 创建表失败,关闭数据库
                sqlite3_close(dataBase);
                NSAssert1(0, @"创建表失败:%s",errorMsg);
           }
           
           NSLog(@"创建表成功");
       }
    }
}

 

插入数据

- (void)Insert
{
   // ?号表示一个未定的值
   NSString *sql = @"INSERT OR REPLACE INTO STUDENT (NAME, ADDRESS,PHONE) VALUES (?,?,?)";
   if (sql && 0 != sql.length)
    {
       [self setSQLitePath];
       
       if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
       {
           // 打开数据库
           sqlite3 *dataBase; // sqlite3
           const char *fileName = [self.filePath UTF8String];
            int openStatus = sqlite3_open(fileName,&dataBase);
           if (openStatus != SQLITE_OK)
           {
                // 数据库打开失败,关闭数据库
                sqlite3_close(dataBase);
                NSAssert(0, @"打开数据库失败");
               
               NSLog(@"打开数据库失败");
           }
           
           NSLog(@"打开数据库成功");
           
           
           const char *execSql = [sql UTF8String];
           sqlite3_stmt *statment;
           int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1,&statment, nil); // 接口把一条SQL语句解析到statement结构里去. 使用该接口访问数据库是当前比较好的的一种方法
           if (execStatus == SQLITE_OK)
           {
                NSLog(@"插入更新表成功");
               
                // 绑定参数开始
                // 这里的数字1,2,3代表上面的第几个问号,这里将三个值绑定到三个绑定变量
                sqlite3_bind_text(statment, 1,[@"zhangshaoyu" UTF8String], -1, NULL);
                sqlite3_bind_text(statment, 2,[@"meizhou" UTF8String], -1, NULL);
                sqlite3_bind_text(statment, 3,[@"13800138000" UTF8String], -1, NULL);
               
                // 执行SQL语句 执行插入
                if (sqlite3_step(statment) !=SQLITE_DONE)
                {
                    NSAssert(NO, @"插入更新表失败。");
                }
                else
                {
                   NSLog(@"插入更新表成功");
                }
           }
           else
           {
                NSLog(@"插入更新表失败");
           }
           
           // 释放sqlite3_stmt对象资源
           sqlite3_finalize(statment);
           
           // 关闭数据库
           sqlite3_close(dataBase);
       }
    }
}

 

修改更新数据

- (void)Update
{
   NSString *sql = @"UPDATE STUDENT SET ADDRESS = ? where NAME =?";
   
   if (sql && 0 != sql.length)
    {
       [self setSQLitePath];
       
        if ([[NSFileManager defaultManager]fileExistsAtPath:self.filePath])
       {
           // 打开数据库
           sqlite3 *dataBase; // sqlite3
           const char *fileName = [self.filePath UTF8String];
           int openStatus = sqlite3_open(fileName, &dataBase);
           if (openStatus != SQLITE_OK)
           {
                // 数据库打开失败,关闭数据库
                sqlite3_close(dataBase);
                NSAssert(0, @"打开数据库失败");
               
                NSLog(@"打开数据库失败");
           }
           
           NSLog(@"打开数据库成功");
           
           const char *execSql = [sql UTF8String];
           sqlite3_stmt *statment;
           int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1,&statment, nil);
           if (execStatus == SQLITE_OK)
           {
                NSLog(@"更新表成功");
               
                // 绑定text类型的数据库数据
                // 这里的数字1,2,3代表第几个问号。这里只有1个问号,这是一个相对比较简单的数据库操作,真正的项目中会远远比这个复杂
                sqlite3_bind_text(statment, 1,[@"meizhouWUHUA" UTF8String], -1, NULL);
                sqlite3_bind_text(statment, 2,[@"zhangshaoyu" UTF8String], -1, NULL);
               
                // 执行插入
                if (sqlite3_step(statment) !=SQLITE_DONE)
                {
                   NSAssert(NO, @"更新表失败。");
                }
                else
                {
                    NSLog(@"更新表成功");
                }
           }
           else
           {
                NSLog(@"更新表失败");
           }
           
           // 释放sqlite3_stmt对象资源
           sqlite3_finalize(statment);
           
           // 关闭数据库
           sqlite3_close(dataBase);
       }
    }
}

 

查找数据

- (void)Select
{
   NSString *sql = @"SELECT * FROM STUDENT";
   if (sql && 0 != sql.length)
    {
       [self setSQLitePath];
       
       if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
       {
           // 打开数据库
           sqlite3 *dataBase; // sqlite3
           const char *fileName = [self.filePath UTF8String];
           int openStatus = sqlite3_open(fileName, &dataBase);
           if (openStatus != SQLITE_OK)
           {
                // 数据库打开失败,关闭数据库
                sqlite3_close(dataBase);
                NSAssert(0, @"打开数据库失败");
               
                NSLog(@"打开数据库失败");
           }
           
           NSLog(@"打开数据库成功");
           
           const char *execSql = [sql UTF8String];
           sqlite3_stmt *statment;
           int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1,&statment, nil);
           if (execStatus == SQLITE_OK)
           {
                NSLog(@"查询成功");
               
                // 查询成功,执行遍历操作
                // 查询结果集中一条一条的遍历所有的记录,这里的数字对应的是列值,注意这里的列值,跟上面sqlite3_bind_text绑定的列值不一样!一定要分开,不然会crash,只有这一处的列号不同,注意!
                while(sqlite3_step(statment) ==SQLITE_ROW)
                {
                    const char *NAME = (char*)sqlite3_column_text(statment, 0);
                    if (NAME != NULL)
                    {
                        NSString *name =[[NSString alloc] initWithUTF8String:NAME];
                        NSLog(@"NAME%@", name);
                    }
                   
                    char *ADDRESS = (char*)sqlite3_column_text(statment, 1);
                    if (ADDRESS != NULL)
                    {
                        NSString *address =[[NSString alloc] initWithUTF8String:ADDRESS];
                        NSLog(@"ADDRESS%@", address);
                    }
                   
                    char *PHONE = (char*)sqlite3_column_text(statment, 2);
                    if (PHONE != NULL)
                    {
                        NSString *phone =[[NSString alloc] initWithUTF8String:PHONE];
                        NSLog(@"PHONE%@", phone);
                    }
                }
           }
           else
           {
                NSLog(@"查询失败");
           }
           
           // 释放sqlite3_stmt对象资源
           sqlite3_finalize(statment);
           
           // 关闭数据库
           sqlite3_close(dataBase);
       }
    }
}

 

删除数据

- (void)Delete
{
//   NSString *sql = @"DELETE FROM STUDENT"; // 方法1
   NSString *sql = @"DELETE FROM STUDENT where NAME = ?"; // 方法2
   if (sql && 0 != sql.length)
    {
       [self setSQLitePath];
       
       if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
       {
           // 打开数据库
           sqlite3 *dataBase; // sqlite3
           const char *fileName = [self.filePath UTF8String];
            int openStatus = sqlite3_open(fileName,&dataBase);
           if (openStatus != SQLITE_OK)
           {
                // 数据库打开失败,关闭数据库
                sqlite3_close(dataBase);
                NSAssert(0, @"打开数据库失败");
               
               NSLog(@"打开数据库失败");
           }
           
           NSLog(@"打开数据库成功");
           
           const char *execSql = [sql UTF8String];
           sqlite3_stmt *statment;
           int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1, &statment,nil);
           if (execStatus == SQLITE_OK)
           {
                // 绑定text类型的数据库数据
                // 这里的数字1,2,3代表第几个问号。这里只有1个问号,这是一个相对比较简单的数据库操作,真正的项目中会远远比这个复杂
                sqlite3_bind_text(statment, 1,[@"zhangshaoyu" UTF8String], -1, NULL);
               
                // 执行删除
                if (sqlite3_step(statment) !=SQLITE_DONE)
                {
                    NSAssert(NO, @"删除数据失败。");
                    NSLog(@"删除数据失败");
                }
                else
                {
                    NSLog(@"删除数据成功");
                }
           }
           else
           {
                NSLog(@"删除数据失败");
           }
           
           // 释放sqlite3_stmt对象资源
           sqlite3_finalize(statment);
            
           // 关闭数据库
           sqlite3_close(dataBase);
       }
    }
}

 

删除表

- (void)DeleteTable
{
   NSString *sql = @"DROP TABLE STUDENT";
   if (sql && 0 != sql.length)
    {
       [self setSQLitePath];
       
       if ([[NSFileManager defaultManager] fileExistsAtPath:self.filePath])
       {
           // 打开数据库
           sqlite3 *dataBase; // sqlite3
           const char *fileName = [self.filePath UTF8String];
           int openStatus = sqlite3_open(fileName, &dataBase);
           if (openStatus != SQLITE_OK)
           {
                // 数据库打开失败,关闭数据库
                sqlite3_close(dataBase);
                NSAssert(0, @"打开数据库失败");
               
                NSLog(@"打开数据库失败");
           }
           
           NSLog(@"打开数据库成功");
           
           const char *execSql = [sql UTF8String];
           sqlite3_stmt *statment;
           int execStatus = sqlite3_prepare_v2(dataBase, execSql, -1,&statment, nil);
           if (execStatus == SQLITE_OK)
           {
                // 执行删除
                if (sqlite3_step(statment) !=SQLITE_DONE)
                {
                    NSAssert(NO, @"删除表失败。");
                    NSLog(@"删除表失败");
                }
                else
                {
                    NSLog(@"删除表成功");
                }
           }
           else
           {
                NSLog(@"删除表失败");
           }
           
           // 释放sqlite3_stmt对象资源
           sqlite3_finalize(statment);
            
           // 关闭数据库
           sqlite3_close(dataBase);
       }
    }
}


 

数据查看



 

注意事项:

1、由于sqlite3是基于C语言编写的,而不是纯粹的object-c,所以有关字符串,我们不能使用NSString,因为它不识别,所以只能用c语言的字符串,char*,好在Nsstring提供了转换的方法,那就是 UTF8String。如:

NSString*sql = @"DELETE FROM STUDENT where NAME = ?";

constchar *execSql = [sql UTF8String];

2sql语句中,不确定值使用?符号。如:

NSString*sql = @"DELETE FROM STUDENT where NAME = ?";

3、提取查询数据函数中的数字表示sql语句中的第几列(0~N)。如:

表示第1列:constchar *NAME = (char *)sqlite3_column_text(statment, 0);

4、绑定数据时函数中的数字表示sql语句中的第几个值。如:

NSString*sql = @"INSERT OR REPLACE INTO STUDENT (NAME, ADDRESS, PHONE) VALUES(?,?,?)";

表示第1个值:sqlite3_bind_text(statment,1, [@"zhangshaoyu" UTF8String], -1, NULL);

表示第2个值:sqlite3_bind_text(statment,2, [@"meizhou" UTF8String], -1, NULL);

表示第3个值:sqlite3_bind_text(statment,3, [@"13510213244" UTF8String], -1, NULL);

5、创建表时,必须设置一个主键PRIMARY KEY。如:

NSString*sql = @"CREATE TABLE IF NOT EXISTS STUDENT(NAME TEXT PRIMARY KEY, ADDRESSTEXT, PHONE TEXT)";



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325847107&siteId=291194637