一个简单将数据进行封装,使用时仅需要提供相应的SQL语句即可。
(具体代码下载)
https://github.com/kuangshiliunian/DataBase
首先导入系统自带的libsqlite3.dylib(必须)
如下图
导入类DataBaseHelper.h(代码应用,按需求自己设计)
//建表
//在AppDelegate.m中
//封装的数据库对象
DataBaseHelper* daHelper = [DataBaseHelper sharedDataBaseHelper];
//创建数据库文件路径
[daHelper dbFileNameWithName:@"contact"];
//建表
NSString* createTableSql = @"create table if not exists contacts (name text,tellnum text,gender text,age integer,userimage text)";
BOOL isSuccess = [daHelper noQueryWithSql:createTableSql];
//判断建表
if (isSuccess) {
NSLog(@"建表成功");
}else{
NSLog(@"建表失败");
}
//插入命令
NSString* inserSql = [NSString stringWithFormat:@"insert into contacts (name,tellnum,gender,age,userimage) values ( '%@', '%@', '%@', %ld,'%@')",self.name.text,self.tellNum.text,self.gender.text,[self.age.text integerValue],imageString];
//数据库执行插入数据命令
BOOL isInsert = [daHelper noQueryWithSql:inserSql];
//判断插入数据库
if (isInsert) {
NSLog(@"增加联系人成功");
}else{
NSLog(@"增加联系人失败");
}
//修改命令
NSString* updateSql = [NSString stringWithFormat:@"update contacts set name='%@', tellnum='%@', gender='%@', age=%ld,userimage='%@' where name='%@' or tellnum='%@' or gender='%@' or age=%d or userimage='%@'",self.name.text,self.tellNum.text,self.gender.text,[self.age.text integerValue],imageString_1,self.contact.name,self.contact.tellNum,self.contact.gender,self.contact.age,imageString];
//数据库执行修改命令
BOOL isUpdate = [daHelper noQueryWithSql:updateSql];
//查询命令
DataBaseHelper* dbHelper = [DataBaseHelper sharedDataBaseHelper];
NSArray* resultArray = [dbHelper queryWithSql:[NSString stringWithFormat:@"select * from contact where age ='%ld'",12]];
if (resultArray.count) {
NSLog(@"获得数据");
}else{
NSLog(@"无数据");
}
//删除命令
//将数据从数据库删除
DataBaseHelper* dbHelper = [DataBaseHelper sharedDataBaseHelper];
BOOL isSuccess = [dbHelper noQueryWithSql:[NSString stringWithFormat:@"delete from collection where age ='%ld'",12]];
//删除成功
if (isSuccess) {
NSLog(@"删除数据成功");
}else{
NSLog(@"删除数据失败");
}