一、简单的语句
SQLite
1.创建表、删除表
2.添加、删除、修改、查找----数据
3.常用的SQL语句
4.创建表格 : create table student ( name text, sex text, age integer)
(创建名为Student的表格 内容为 name ***)
1** text:字符串 2** integer : int 3** real :flout 4** blob : data
创建表格的时候指定主键(唯一标识一条记录的字段,不能重复):默认行数为主键(不 指定)
create table boss (name text , age integer , number integer primary key)
1.添加数据(往表里面) (所有的列)
各个值之间要用 , 隔开 text类型要用 ''
insert into student values ('hehe','m',18)
2.给指定的列添加数据 : insert into student (name,sex) values ('haha','f')
3.删除数据,如果根据主键来删除,最多只能删除一条
delete from boss where number = 1
4.如果根据某个字段删除数据,如果不是根据主键,所有这个字段一样的记录都会被删掉
delete from boss where name = 'ppp'
修改student 表中 name = 'ppp'的数据 将它的 sex 改为 f|m
update student set sex = 'f|m' where name = 'ppp'
5.查找【字段】(从student查找年龄为19所有人得名字)
select name from student where age = 19
查找一条【记录】的信息
select * from student where age = 19
查到表格的所有【记录】
select * from student
6.查找sex字段中 以f开头的模糊 (模糊查找)
select * from student where sex like 'f%'
7.删除表(boss)
drop table boss
二、代码演示:
1.要在工程使用SQLite,需要导入 libsqlite3.0.dylib 动态库
2.建立一个学生的类Student3.建立一个数据库管理者
主要演示的代码是数据库管理者:
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@class Student ;
@interface DataBaseManager : NSObject
//实例变量
{
//数据指针,通过指针可以操作对应的数据库
sqlite3 *dbPoint ;
}
//单例方法
+(instancetype)shareInstance;
//多线程下保证数据库安全的单例写法
+(instancetype)shareInstanceAnotherWay;
//GCD保证
+(instancetype)shareInstanceGCD;
//打开数据库
-(void)openDb;
//关闭数据库
-(void)closeDb;
//创建表
-(void)createTable;
//插入列
-(void)createAlterTable;
//删除表
-(void)dropTable;
//添加数据(插入学生)
-(void)insertStudent:(Student *)stu ;
//写入二进制数据
-(void)insertStudentAnotherPose:(Student *)stu ;
//删除数据(删除学生)
-(void)deleteStudent:(Student *)stu ;
//修改信息
-(void)updateStudent:(Student *)stu withName:(NSString *)name ;
//查找所有学生
-(NSMutableArray *)selectAllStudent;
@end
实现部分:
#import "DataBaseManager.h"
#import "Student.h"
@implementation DataBaseManager
/*
单例对象:
1.在不同类中通过单例方法获取的都是一个对象
2.保证多线程开发中数据库的安全
3.可以使用单例来传值
4.
*/
+(instancetype)shareInstance{
//单例方法的实现
//创建一个空对象
static DataBaseManager *dbManger = nil ;
//如果为空,则创建一个对象
if (nil == dbManger) {
dbManger = [[DataBaseManager alloc]init];
}
return dbManger ;
}
//安全锁 单例
+(instancetype)shareInstanceAnotherWay{
static DataBaseManager *dbManger = nil ;
@synchronized(self){ //加线程锁,线程锁中的代码会受到保护,保证此时没有其它线程访问self对象
if (dbManger == nil) {
dbManger = [[DataBaseManager alloc]init];
}
}
return dbManger ;
}
//GCD
+(instancetype)shareInstanceGCD{
static DataBaseManager *dbManger = nil ;
//声明一个只执行一次的多线程
static dispatch_once_t once ;
dispatch_once(&once, ^{
dbManger = [[DataBaseManager alloc]init];
});
return dbManger ;
}
//打开数据库
-(void)openDb{
//想要打开的数据可路径
NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"student.db"];
NSLog(@"%@",dbPath);
/*
参数1:想要打开的数据库的路径,需要的是C语言的字符串
参数2:将dbPoint 指针和数据库绑定,通过dbPoint可以访问该路径下的数据库
如果该路径下不存在对应的数据库,系统会自动创建一个数据库
*/
int result = sqlite3_open(dbPath.UTF8String, &dbPoint);
if (SQLITE_OK == result ) {
NSLog(@"数据库打开成功");
}
else
{
NSLog(@"数据库打开失败");
}
}
//关闭数据库
-(void)closeDb{
int result = sqlite3_close(dbPoint) ;
[self judgeWithResult:result action:@"关闭数据库"];
}
-(void)judgeWithResult:(int)result action:(NSString *)actionStr{
if (result == SQLITE_OK) {
NSLog(@"%@成功",actionStr);
}
else
{
NSLog(@"%@失败",actionStr);
}
}
//创建表
-(void)createTable{
[self openDb];
NSString *sqlStr = @"create table students (name text , sex text , number integer primary key)";
/**
* 参数1:要使用的是哪一个数据库
* 参数2:想对数据做什么操作 SQL语句
* 参数3/4:系统预留的参数
* 参数5:错误信息
*
* @return <#return value description#>
*/
char *error ;
int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
NSLog(@"%s",error);
[self judgeWithResult:result action:@"创建表"];
//销毁指针
sqlite3_free(error) ;
[self closeDb];
}
//插入列
-(void)createAlterTable{
[self openDb];
NSString *string = @"alter table students add (image blob) ";
char *error ;
int result = sqlite3_exec(dbPoint, string.UTF8String, NULL, NULL, &error);
[self judgeWithResult:result action:@"插入列"];
sqlite3_free(error);
[self closeDb];
}
//删除表
-(void)dropTable{
[self openDb];
NSString *sqlStr = @"drop table students " ;
char *error1 ;
int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error1);
NSLog(@"%s",error1);
[self judgeWithResult:result action:@"删除表"];
//销毁指针
sqlite3_free(error1) ;
[self closeDb];
}
//添加学生
-(void)insertStudent:(Student *)stu{
[self openDb];
NSString *sqlStr = [NSString stringWithFormat:@"insert into students values ('%@','%@',%ld)",stu.name,stu.sex,stu.number];
char *error ;
int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
[self judgeWithResult:result action:@"插入学生"];
sqlite3_free(error);
[self closeDb];
}
-(void)insertStudentAnotherPose:(Student *)stu{
[self openDb];
//跟随指针
sqlite3_stmt *stmt = nil ;
int result = sqlite3_prepare(dbPoint, "insert into students (name,sex,number,image) values (?,?,?,?)", -1, &stmt, NULL);
if (result == SQLITE_OK) {
/*
如果SQL没有问题,则绑定插入的数据 (写入)
参数1:把柄 stmt
参数2:给SQL语句中的第几个 ?赋值
参数3:写入的内容
参数4:写入数据的长度
参数5:系统预留的参数
*/
sqlite3_bind_text(stmt, 1, stu.name.UTF8String, -1, NULL);
sqlite3_bind_text(stmt, 2, stu.sex.UTF8String, -1, NULL);
sqlite3_bind_int(stmt, 3, (int)stu.number);
/*
UIImage需要转成NSData才能写入数据库
参数1:想要转得那张图片
参数2:压缩程度(0~1),压缩数值越大,图片质量越低(压缩完之后再取出来的图片)
*/
NSData *data = UIImageJPEGRepresentation(stu.image, 0.6);
//参数3:首字节起始位置的指针
//参数4:二进制数据的长度,就是有多少个字节
sqlite3_bind_blob(stmt, 4, [data bytes], (int)data.length, NULL);
int addResult = sqlite3_step(stmt);
if (addResult == SQLITE_OK) {
NSLog(@"插入学生图片成功");
}
}
sqlite3_finalize(stmt);
[self closeDb];
}
//删除学生
-(void)deleteStudent:(Student *)stu{
[self openDb];
NSString *sqlStr = [NSString stringWithFormat:@"delete from students where number = %ld ",stu.number];
char *error ;
int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
[self judgeWithResult:result action:@"删除学生"];
sqlite3_free(error);
[self closeDb];
}
//修改学生
-(void)updateStudent:(Student *)stu withName:(NSString *)name{
[self openDb];
NSString *sqlStr = [NSString stringWithFormat:@"update students set name = '%@' where number = %ld ",stu.name ,stu.number];
char *error ;
int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, &error);
[self judgeWithResult:result action:@"修改学生"];
sqlite3_free(error);
[self closeDb];
}
//查找所有学生
-(NSMutableArray *)selectAllStudent{
[self openDb];
NSMutableArray *stuArray = [NSMutableArray array];
NSString *sqlStr = @"select * from students" ;
//创建指针(数据库的状态指针,数据库执行语句的所有结果都保存在这个指针里面)
sqlite3_stmt *stmt= nil ;
/*
*执行SQL语句,并且将执行结果保存在stmt中
参数1:数据库指针
参数2:要执行的SQL语句
参数3:限制SQL语句的长度,-1就是不限制
参数4:stmt指针
参数5:
*/
int result = sqlite3_prepare(dbPoint, sqlStr.UTF8String, -1, &stmt, NULL);
if (result == SQLITE_OK) {
//遍历stmt中的数据,一行一行的遍历
while (sqlite3_step(stmt) == SQLITE_ROW) {
Student *stu = [[Student alloc]init];
/*
参数1:状态指针
参数2:去第几列的值(从0开始计数)
*/
const unsigned char *nameChar = sqlite3_column_text(stmt, 0);
//将C语言的字符串转化为OC字符串
NSString *name = [NSString stringWithUTF8String:(const char *)nameChar];
stu.name = name ;
stu.sex = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(stmt, 1)];
stu.number = sqlite3_column_int(stmt, 2) ;
//数据库取出的 sqlite3_column_blob(stmt, 3)的二进制数据 是 const void * 类型 要转化为NSData类型
stu.image = [UIImage imageWithData:[NSData dataWithBytes:sqlite3_column_blob(stmt, 3) length:1]];
[stuArray addObject:stu];
[stu release];
}
}
//保证同一时间只有一个
sqlite3_finalize(stmt) ;
[self closeDb];
return stuArray ;
}
@end
简单调用的实现部分:
#pragma mark --打开数据库
-(void)initSQLite{
//初始化一个单例对象
DataBaseManager *dbManager = [DataBaseManager shareInstance];
//打开数据库
// [dbManager openDb];
//关闭数据库
// [dbManager closeDb];
//创建表格
[dbManager createTable];
//删除表格
// [dbManager dropTable];
//插入列
[dbManager createAlterTable];
//初始化对象
// Student *stu = [[Student alloc]initWithName:@"小明" Sex:@"男" Number:18];
// [dbManager insertStudent:stu];
//
// Student *stu1 = [[Student alloc]initWithName:@"小强" Sex:@"女" Number:20];
Student *stu = [[Student alloc]initWithName:@"小明" Sex:@"男" Number:28 Image:nil];
stu.image = [UIImage imageNamed:@"06.jpg"];
//插入学生
[dbManager insertStudent:stu];
//写入二进制数据
[dbManager insertStudentAnotherPose:stu];
//删除学生
// [dbManager deleteStudent:stu];
//更新
// [dbManager updateStudent:stu withName:@"小明"];
//查询
// NSArray *array = [dbManager selectAllStudent];
//
// for (Student *stu in array) {
// NSLog(@"%@ %@ %ld",stu.name,stu.sex,stu.number);
// }
}