Sqlite数据库简介

时间:2024-04-23 20:51:32

在应用sqlite之前需要添加sqlite库,那么我们就会发现有3和3.0的区别,开始我也并不懂,后才知道:

实际上libsqlite3.dylib本身是个链接,它指向libsqlite3.0.dylib。
也就是说在项目里如果你添加libsqlite3.dylib和添加libsqlite3.0.dylib其实是添加了同一个文件,从而使得该库常新。

为了方便管理数据库,并且使之唯一不出现混乱,我们尝尝将sqlite定义一个单例

 static  MySqliteManager *manager = nil;
+(MySqliteManager *)shareManager{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[MySqliteManager alloc]init];
});
return manager;
}

singleton

sqlite数据库可以分为以下几部分:

1、打开数据库

(1)如果没有该文件则创建空的sqlite后缀文件。

(2)允许对数据进行操作

- (void)open{
//确定数据库的存放路径
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; // sqlite路径
NSString *sqlitePath = [documentPath stringByAppendingString:@"dataBase.sqlite"];
NSLog(@"path == %@",sqlitePath);
//打开数据库
int result = sqlite3_open(sqlitePath.UTF8String, &db);//参数1:C中字符串,(使用点方法UTF8String转换 , ) // 判断打开是否成功
if (result == SQLITE_OK) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"打开成功" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"打开失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show]; }
}

open

2、关闭数据库

(1)禁止对数据进行任何操作

  - (void)close{
int result = sqlite3_close(db);
if (result == SQLITE_OK) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"关闭成功" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"关闭失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show]; }
}

close

3、创建表

(1)创建对应的数据结构

(2)其中 primary key 指唯一,不可重复

  - (void)create{
//sql语句
NSString *sqlString = @"create table Person ( id integer primary key, name text ,age integer)";
// 执行sql语句 char *error;
sqlite3_exec(db, sqlString.UTF8String, nil, nil, &error);
if (error == nil) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"创建表成功" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"创建表失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}
}

creat

4、插入数据

(1)添加具体的数据实例

   //sql语句
NSString *sqlString = @"insert into Person ('name','age') values ('张三',18)";
// 执行语句
char *error = nil;
sqlite3_exec(db, sqlString.UTF8String, nil, nil, &error);
if (error == nil) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"插入成功" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"插入失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}

insert

5、更新数据

(1)修改数据

 //sql语句
NSString *sqlString = @"update Person set 'name' = '李四' where id = 1";
//执行sql语句 char *error = nil;
sqlite3_exec(db, sqlString.UTF8String, nil, nil, &error);
if (error == nil) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"更新成功" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"更新失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}

update

6、删除数据

 //sql语句
NSString *sqlString = @"delete from Person where id = 1";
//执行sql语句
char *error = nil;
sqlite3_exec(db, sqlString.UTF8String, nil, nil, &error);
if (error == nil) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"删除成功" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}else{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"数据库执行结果" message:@"删除失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
[alertView show];
}

delete

7、查询数据

//sql语句
NSString *sqlString = @"select *from Person";
//准备sql语句 sqlite3_stmt *stmt = nil;//数据库管理指针
sqlite3_prepare(db, sqlString.UTF8String, -/*-1代表自动计算语句长度*/, &stmt, nil); // 单步执行语句
while (sqlite3_step(stmt) == SQLITE_ROW) {
int ID = sqlite3_column_int(stmt, );//第二个参数是参数位置
const unsigned char * name = sqlite3_column_text(stmt, );
NSString *nameString = [NSString stringWithUTF8String:(const char *)name];
int age= sqlite3_column_int(stmt, ); NSLog(@"id = %d \n name = %@ \n age = %d",ID,nameString,age);
}
// 释放管理语句
sqlite3_finalize(stmt);

select

常用语句:

1 首先获取iPhone上sqlite3的数据库文件的地址

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"database_name"];

打开iPhone上的sqlite3的数据库文件

sqlite3 *database;
sqlite3_open([path UTF8String], &database);

3 准备sql文---sql语句

sqlite3_stmt *stmt;
const char *sql = "SELECT * FROM table_name WHERE pk=? and name=?";
sqlite3_prepare_v2(database, sql, -1, &stmt, NULL);

邦定参数

// 邦定第一个int参数
sqlite3_bind_int(stmt, 1, 1);
// 邦定第二个字符串参数
sqlite3_bind_text(stmt, 2, [title UTF8String], -1, SQLITE_TRANSIENT);

执行sql文

sqlite3_step(stmt);

释放sql文资源

sqlite3_finalize(stmt);

关闭iPhone上的sqlite3的数据库

sqlite3_close(database);

http://hi.baidu.com/clickto/blog/item/0c6904f787c34125720eec87.html

以下演示一下使用sqlite的步骤,先创建一个数据库,然后查询其中的内容。2个重要结构体和5个主要函数:

sqlite3               *pdb, 数据库句柄,跟文件句柄FILE很类似

sqlite3_stmt      *stmt, 这个相当于ODBC的Command对象,用于保存编译好的SQL语句

sqlite3_open(),   打开数据库

sqlite3_exec(),   执行非查询的sql语句

sqlite3_prepare(), 准备sql语句,执行select语句或者要使用parameter bind时,用这个函数(封装了sqlite3_exec).

Sqlite3_step(), 在调用sqlite3_prepare后,使用这个函数在记录集中移动。

Sqlite3_close(), 关闭数据库文件

还有一系列的函数,用于从记录集字段中获取数据,如

sqlite3_column_text(), 取text类型的数据。

sqlite3_column_blob(),取blob类型的数据

sqlite3_column_int(), 取int类型的数据

PreparedStatement方式处理SQL请求的过程
特点:可以绑定参数,生成过程。执行的时候像是ADO一样,每次返回一行结果。

1. 首先建立statement对象:
int sqlite3_prepare(
sqlite3 *db,            /* Database handle */
const char *zSql,       /* SQL statement, UTF-8 encoded */
int nBytes,             /* Length of zSql in bytes. */
sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);

2. 绑定过程中的参数(如果有没有确定的参数)
int sqlite3_bind_xxxx(sqlite3_stmt*, int, ...);
第二个int类型参数-表示参数的在SQL中的序号(从1开始)。
第三个参数为要绑定参数的值。
对于blob和text数值的额外参数:
第四参数是字符串(Unicode 8or16)的长度,不包括结束'\0'。
第五个参数,类型为void(*)(void*),表示SQLite处理结束后用于清理参数字符串的函数。
没有进行绑定的未知参数将被认为是NULL。

3. 执行过程
int sqlite3_step(sqlite3_stmt*);
可能的返回值:
*SQLITE_BUSY:   数据库被锁定,需要等待再次尝试直到成功。
*SQLITE_DONE:   成功执行过程(需要再次执行一遍以恢复数据库状态)
*SQLITE_ROW:    返回一行结果(使用sqlite3_column_xxx(sqlite3_stmt*,, int iCol)得到每一列的结果。
再次调用将返回下一行的结果。
*SQLITE_ERROR:  运行错误,过程无法再次调用(错误内容参考sqlite3_errmsg函数返回值)
*SQLITE_MISUSE: 错误的使用了本函数(一般是过程没有正确的初始化)

4. 结束的时候清理statement对象
int sqlite3_finalize(sqlite3_stmt *pStmt);
应该在关闭数据库之前清理过程中占用的资源。

5. 重置过程的执行 
int sqlite3_reset(sqlite3_stmt *pStmt);
过程将回到没有执行之前的状态,绑定的参数不会变化。