分享一段ios数据库代码。包括创建、升级、增删查改。

里面的那些类不必细究,主要是数据库的代码100%可用。

数据库升级部分,使用switch,没有break,低版本一次向高版本修改。

//  DB.h
//iukey
#import <Foundation/Foundation.h>
#import "sqlite3.h"
#import "User.h"
#import "ChatInfo.h"
#import "DescInfo.h"
@interface DBHelper : NSObject{
sqlite3* db;//数据库句柄
// @public DBHelper *instance;
} @property(nonatomic,assign)sqlite3* db;
- (BOOL)insertUserWithTUsersName:(NSString*)name account:(NSString*)account pwd:(NSString*)pwd;
- (NSMutableArray*)quary:(NSString*)str;//查询 - (NSString*)getFilePath;//获取数据库路径
- (BOOL)createDB;//创建数据库
- (BOOL)createTable:(NSString*) creteSql;//创建表
- (User*)getUserWithTUsersByAccount:(NSString* )account;
- (BOOL)updateUserPwdWithTUsers:(NSString*)pwd byAccount:(NSString*)account ;
//+ (DBHelper*) getDBhelperInstance;
- (BOOL)deleteItemWithTable:(NSString*)table_ ByKey:(NSString*)key_ ;
-(BOOL)insertChatRecordWithTChatRecordByChatInfo:(ChatInfo*)ci owner:(NSString *)owner;
- (int)getRecordCountWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid owner:(NSString *)owner;
- (NSMutableArray*)getChatInfoWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid fromIndex:(int)fromIndex count:(int)count owner:(NSString *)owner;
- (BOOL)deleteChatInfoWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid owner:(NSString *)owner; -(NSMutableDictionary*)getRecordCountNotREadWithTChatRecord:(NSString*)toJid owner:(NSString *)owner;
-(BOOL)updateRecordCountNotReadWithChatRecord:(NSString *)fromJid;
-(NSMutableArray*)getRecordNotReadWithTChatRecordFromJid:(NSString*)fromJid owner:(NSString *)owner;
//history
-(BOOL)insertHistoryRecordWithTHistoryRecordByDescInfo:(DescInfo*)di account:(NSString*)account routerjid:(NSString *)routerjid;
- (NSMutableArray*)getHistoryRecordWithTHistoryRecordByAccount:(NSString* )account routerjid:(NSString *)routerjid;
- (BOOL)deleteHistoryWithTHistoryRecordByDeviceType:(NSString *)deviceType account:(NSString* )account routerjid:(NSString *)routerjid;
- (BOOL)deleteHistoryWithTHistoryRecordById:(int)c_id account:(NSString* )account routerjid:(NSString *)routerjid;
- (NSMutableArray*)getHistoryRecordWithTHistoryRecordByUDN:(NSString* )UDN withAccount:(NSString* )account routerjid:(NSString *)routerjid;
-(BOOL)updateHistoryCountNotReadWithHistoryRecordByDeviceType:(NSString *)deviceType account:(NSString* )account routerjid:(NSString *)routerjid;
-(int)getHistoryCountNotReadWithHistoryRecordByAccount:(NSString *)account routerjid:(NSString *)routerjid; @end
//  DB.m
//iukey
#import "DBHelper.h"
#import "YHConfig.h"
#import "DescInfo.h"
#import "FromJid.h"
// tid ----table index id
@implementation DBHelper static NSString *createTB_user=@"create table if not exists t_users (c_account text primary key ,c_name text,c_pwd text)"; /*
info_ key-value
db_version --1
...
*/
static NSString *createTB_info=@"create table if not exists t_info (c_key text primary key ,c_value text)";
/*
c_time 存储1970秒数
*/
static NSString *createTB_chat_record=@"create table if not exists t_chat_record (c_id integer primary key autoincrement,c_from_jid text,c_to_jid text,c_chat_time integer,c_msg text,c_has_read integer)"; static NSString *createTB_history_record=@"create table if not exists t_history_record (c_id integer primary key autoincrement,c_deviceType text,c_UDN text,c_friendlyName text,c_history_time integer,c_desc text)"; @synthesize db; - (id)init{
self = [super init];
int dbVersion =;
//检查是否存在数据库文件
if (![self isExistDB]) {
//不存在,则创建
[self createDB];
}else {
//若存在,检测数据库版本,则进行升级, char* info=NULL;
[self getDBInfoValueWithKey:"db_version" value:&info];
if(info == NULL){
return self;
}
dbVersion= atoi(info);
free (info); }
//升级数据库。若第一次创建,则从0开始升级。顺序升级,因此不可以有break
switch (dbVersion) {
case :
//第一次,新建并初始化各表
[self createTable:createTB_user];
//记录版本
[self createTable:createTB_info];
[self setDBInfoValueWithKey:"db_version" value:""];
[self createTable:createTB_chat_record];
[self createTable:createTB_history_record];
case :
[self setDBInfoValueWithKey:"db_version" value:""];
case :
{
NSString *modify=@"alter table t_history_record add column c_user text not null default ''";
[self setDBInfoValueWithKey:"db_version" value:""];
[self execSql:modify];
}
case :
{
NSString *modify=@"alter table t_chat_record add column c_owner text not null default ''";
[self setDBInfoValueWithKey:"db_version" value:""];
[self execSql:modify];
}
case :
{
NSString *modify=@"alter table t_history_record add column c_router text not null default ''";
[self setDBInfoValueWithKey:"db_version" value:""];
[self execSql:modify];
}
case :
{
NSString *modify=@"alter table t_history_record add column c_has_read integer not null default ''";
[self setDBInfoValueWithKey:"db_version" value:""];
[self execSql:modify];
}
//注:数据库升级时候,只需要一次添加case即可,同时更新<span style="font-family: Arial, Helvetica, sans-serif;">db_version值</span>
/*
case 3:
{
//先不加密
//1、将db文件移至portrait,并重命名yunho.db->_yunho.png
//2、得到所有的密码,使用base64存储
//3、用户名输入时候能自动检测是否有匹配的密码并实时的显示 // NSString *modify=@"alter table t_history_record add column c_user text not null default ''";
// [self setDBInfoValueWithKey:"db_version" value:" 4"];
// [self execSql:modify];
}
*/
default:
break;
}
return self;
} - (NSString*)getFilePath{//get db path
NSArray *documentsPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask , YES);
NSString *databaseFilePath=[[documentsPaths objectAtIndex:] stringByAppendingPathComponent:[YHConfig DBName ]];
return databaseFilePath ;
} #pragma mark db manage
- (BOOL)createDB{
int ret = sqlite3_open([[self getFilePath] UTF8String], &db);//打开数据库,数据库不存在则创建
if (SQLITE_OK == ret) {//创建成功
sqlite3_close(db);//关闭
return YES;
}else{
return NO;//创建失败
}
}
-(BOOL) isExistDB{
NSFileManager* fm = [[[NSFileManager alloc] init]autorelease];
return [fm fileExistsAtPath:[self getFilePath] ];
}
/*
create table dictionary(ID integer primary key autoincrement,en nvarchar(64),cn nvarchar(128),comment nvarchar(256))
*/
- (BOOL)dropTableWithTableName:(NSString*) tableName{
NSString* dropSql = [[NSString alloc] initWithFormat:@"delete table %@",tableName];
return [self execSql:[dropSql autorelease]];
}
- (BOOL)createTable:(NSString*) creteSql{
return [self execSql:creteSql];
}
-(BOOL) execSql:(NSString*) creteSql{
char* err;
const char* sql = [creteSql UTF8String];//创建表语句
if (sql==NULL) {
return NO;
}
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){
return NO;
} if (SQLITE_OK == sqlite3_exec(db, sql, NULL, NULL, &err)) {//执行创建表语句成功
sqlite3_close(db);
return YES;
}else{//创建表失败
return NO;
} }
//"select * from dictionary where en like ? or cn like ? or comment like ?;";//查询语句
//TODO
- (NSMutableArray*)quary:(NSString *) querySql{ if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){
return nil;
}
const char* sql = [querySql UTF8String];//查询语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
// sqlite3_bind_text(stmt, 1,[[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL);
// sqlite3_bind_text(stmt, 2, [[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL);
// sqlite3_bind_text(stmt, 3, [[NSString stringWithFormat:@"%%%@%%",str]UTF8String], -1, NULL);
}else{
return nil;
}
NSMutableArray* arr =[[NSMutableArray alloc]init];//存放查询结果
while( SQLITE_ROW == sqlite3_step(stmt) ){//执行
char* _en = (char*)sqlite3_column_text(stmt, );
char* _cn = (char*)sqlite3_column_text(stmt, );
char* _comment = (char*)sqlite3_column_text(stmt, ); NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];//单条纪录
[dict setObject:[NSString stringWithCString:_en encoding:NSUTF8StringEncoding] forKey:@"kEN"];
[dict setObject:[NSString stringWithCString:_cn encoding:NSUTF8StringEncoding] forKey:@"kCN"];
[dict setObject:[NSString stringWithCString:_comment encoding:NSUTF8StringEncoding] forKey:@"kCOMMENT"];
[arr addObject:dict];//插入到结果数组
[dict release];
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return [arr autorelease];//返回查询结果数组
} #pragma mark table t_info manage
- (void)getDBInfoValueWithKey:(const char*)key value:(char**)value{
//TODO
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
printf("%s:%d query error..\n",__FUNCTION__,__LINE__);
return ;
}
const char* sql = "select * from t_info where c_key =?";//查询语句
sqlite3_stmt* stmt; int error = sqlite3_prepare_v2(db, sql, -, &stmt, nil);
if (error==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, ,key, -, NULL);
}else{
printf("%s:%d query error.. %d\n",__FUNCTION__,__LINE__,error);
return;
} if( SQLITE_ROW == sqlite3_step(stmt) ){//执行
char* v= (char*)sqlite3_column_text(stmt, );
*value = strdup(v); }
sqlite3_finalize(stmt);
sqlite3_close(db);
}
- (BOOL)setDBInfoValueWithKey:(const char*)key value:(const char*)value {
char* info=NULL;
[self getDBInfoValueWithKey:key value:&info];
if (info!= NULL) {
//存在,则更新
[self updateDBInfoValueWithKey:key value:value];
}else{
//不存在,插入
[self insertDBInfoValueWithKey:key value:value]; }
free(info);
return YES;
} - (BOOL)insertDBInfoValueWithKey:(const char*)key value:(const char*)value{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){
return NO;
}
const char* sql = "insert into t_info(c_key,c_value) values(?,?);";
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, sql, -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, , key, -, NULL);//绑定参数
sqlite3_bind_text(stmt, , value, -, NULL);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
}
} - (BOOL)updateDBInfoValueWithKey:(const char*)key value:(const char*)value{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){
return NO;
}
const char* sql = "update t_info set c_value = ? where c_key = ?;";
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, sql, -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, , value, -, NULL);
sqlite3_bind_text(stmt, , key, -, NULL);
}else{
return NO;
}
ret = sqlite3_step(stmt);
printf("ret:%d\n",ret);
if (SQLITE_DONE ==ret ) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
}
} #pragma mark table "t_users" manage
- (User*)getUserWithTUsersByAccount:(NSString* )account{ if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
} const char* sql = "select * from t_users where c_account = ?";//查询语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, ,[account UTF8String], -, NULL);
}else{
return nil;
}
User* user = nil;
if( SQLITE_ROW == sqlite3_step(stmt) ){//执行
user = [[[User alloc]init]autorelease];
NSString *name=nil;
NSString *pwd= nil;
if (sqlite3_column_text(stmt, ) != NULL) {
name = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )]; }
if (sqlite3_column_text(stmt, ) != NULL) {
pwd = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
} user.name =name;
user.account= account;
user.pwd = pwd;
} sqlite3_finalize(stmt);
sqlite3_close(db);
return user;
} - (BOOL)insertUserWithTUsersName:(NSString*)name account:(NSString*)account pwd:(NSString*)pwd{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
return NO;
}
const char* sql = "insert into t_users(c_name,c_account,c_pwd) values(?,?,?);";
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, sql, -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, , [name UTF8String], -, NULL);//绑定参数
sqlite3_bind_text(stmt, , [account UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [pwd UTF8String], -, NULL);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
}
} //根据account 修改用户 的name和pwd
- (BOOL)updateUserPwdWithTUsers:(NSString*)pwd byAccount:(NSString*)account {
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
return NO;
}
const char* sql = "update t_users set c_pwd = ? where c_account = ?";
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, sql, -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, , [pwd UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [account UTF8String], -, NULL);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
}
}
#pragma mark table "t_chat_record" manage
-(BOOL)insertChatRecordWithTChatRecordByChatInfo:(ChatInfo*)ci owner:(NSString *)owner{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
return NO;
}
//@"create table if not exists t_chat_record (c_id text primary key ,c_from_jid text,c_to_jid text,c_chat_time integer,c_msg text)";
const char* sql = "insert into t_chat_record(c_from_jid,c_to_jid,c_chat_time,c_msg,c_has_read,c_owner) values(?,?,?,?,?,?);";
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, sql, -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, , [[ci fromJid] UTF8String], -, NULL);//绑定参数
sqlite3_bind_text(stmt, , [[ci toJid] UTF8String], -, NULL);
sqlite3_bind_int(stmt, , (int)[ci.chatTime timeIntervalSince1970] );
sqlite3_bind_text(stmt, , [ci.msg UTF8String], -, NULL);
sqlite3_bind_int(stmt, , [ci hasRead]);
sqlite3_bind_text(stmt, , [owner UTF8String], -, NULL);
log4debug(@"%d",[ci hasRead]);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
} }
//update the count of chat record not read
-(BOOL)updateRecordCountNotReadWithChatRecord:(NSString *)fromJid
{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
const char* sql = "update t_chat_record set c_has_read = 1 where c_from_jid = ?";//修改语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, , [fromJid UTF8String], -, NULL); }else{
return nil;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
} } -(NSMutableArray*)getRecordNotReadWithTChatRecordFromJid:(NSString*)fromJid owner:(NSString *)owner{
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
const char* sql = "select c_chat_time,c_msg from t_chat_record where c_has_read = 0 and c_from_jid =? and c_owner =? order by c_chat_time asc";//查询语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, ,[fromJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[owner UTF8String], -, NULL);
}else{
return nil;
} NSMutableArray* msgs=[[[NSMutableArray alloc]init]autorelease];
while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
NSString *msg=nil;
int chatTime = ;
if (sqlite3_column_text(stmt, ) != NULL) {
msg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )]; }
chatTime = sqlite3_column_int(stmt, );
NSDate * showTime = [NSDate dateWithTimeIntervalSince1970:chatTime];
[msgs addObject:showTime];
[msgs addObject:msg]; } sqlite3_finalize(stmt);
sqlite3_close(db);
return msgs ;
} //get the count of the chat record not read
-(NSMutableDictionary*)getRecordCountNotREadWithTChatRecord:(NSString*)toJid owner:(NSString *)owner
{
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
const char* sql = "select c_from_jid, count(*) from t_chat_record where c_has_read = 0 and c_to_jid =? and c_owner =? group by c_from_jid ";//查询语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, ,[toJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[owner UTF8String], -, NULL);
}else{
return nil;
} NSMutableDictionary* fis=[[[NSMutableDictionary alloc]init]autorelease];
while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
FromJid* fi = [[[FromJid alloc]init]autorelease];
NSString *fromJid=nil;
int noReadCount = ; if (sqlite3_column_text(stmt, ) != NULL) {
fromJid = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
noReadCount = sqlite3_column_int(stmt, ); fi.fromJid = fromJid;
fi.noReadCount = noReadCount;
[fis setObject:fi forKey:fi.fromJid];
} sqlite3_finalize(stmt);
sqlite3_close(db);
return fis ; } //get the count of the chat record
- (int)getRecordCountWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid owner:(NSString *)owner
{
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
//static NSString *createTB_chat_record=@"create table if not exists t_chat_record (c_id integer primary key autoincrement,c_from_jid text,c_to_jid text,c_chat_time integer,c_msg text)";
//不区分from&to,因此两个条件查询
const char* sql = "select count (*) from t_chat_record where ((c_from_jid = ? and c_to_jid=?) or (c_from_jid = ? and c_to_jid=?)) and c_owner = ?";//查询语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, ,[oneJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[anotherJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[anotherJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[oneJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[owner UTF8String], -, NULL);
}else{
return nil;
}
int count=;
if ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
count=sqlite3_column_int(stmt, );
} sqlite3_finalize(stmt);
sqlite3_close(db);
return count ;
} - (NSMutableArray*)getChatInfoWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid fromIndex:(int)fromIndex count:(int)count owner:(NSString *)owner
{
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
//static NSString *createTB_chat_record=@"create table if not exists t_chat_record (c_id integer primary key autoincrement,c_from_jid text,c_to_jid text,c_chat_time integer,c_msg text)";
//不区分from&to,因此两个条件查询
const char* sql = "select * from t_chat_record where ((c_from_jid = ? and c_to_jid=?) or (c_from_jid = ? and c_to_jid=?)) and c_owner = ? order by c_chat_time asc limit ?,? ";//查询语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, ,[oneJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[anotherJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[anotherJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[oneJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[owner UTF8String], -, NULL);
sqlite3_bind_int(stmt, , fromIndex);
sqlite3_bind_int(stmt, , count);
}else{
return nil;
}
NSMutableArray *cis=[[[NSMutableArray alloc]initWithCapacity:]autorelease];
while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
ChatInfo* ci = [[[ChatInfo alloc]init]autorelease];
NSString *fromJid=nil;
NSString *toJid= nil;
NSString *msg=nil;
int time = ;
if (sqlite3_column_text(stmt, ) != NULL) {
fromJid = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
if (sqlite3_column_text(stmt, ) != NULL) {
toJid = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
if (sqlite3_column_text(stmt, ) != NULL) {
time = sqlite3_column_int(stmt, );
}
if (sqlite3_column_text(stmt, ) != NULL) {
msg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
ci.fromJid=fromJid;
ci.toJid=toJid;
ci.chatTime=[NSDate dateWithTimeIntervalSince1970:time];
ci.msg=msg;
[cis addObject:ci];
} sqlite3_finalize(stmt);
sqlite3_close(db);
return cis ;
} - (BOOL)deleteChatInfoWithTChatRecordByoneJid:(NSString* )oneJid anotherJid:(NSString* )anotherJid owner:(NSString *)owner
{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
return NO;
}
NSString* sql = [NSString stringWithFormat:@"delete from t_chat_record where ((c_from_jid = ? and c_to_jid=?) or (c_from_jid = ? and c_to_jid=?)) and c_owner = ?"];
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, [sql UTF8String], -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, ,[oneJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[anotherJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[anotherJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[oneJid UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[owner UTF8String], -, NULL);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
} } #pragma mark table "t_history_record" manage
-(BOOL)insertHistoryRecordWithTHistoryRecordByDescInfo:(DescInfo*)di account:(NSString*)account routerjid:(NSString *)routerjid{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
return NO;
}
//@"create table if not exists t_history_record (c_id text primary key ,c_deviceType text,c_UDN text,c_friendlyName text,c_history_time integer,c_desc text)";
const char* sql = "insert into t_history_record(c_deviceType,c_UDN,c_friendlyName,c_history_time,c_desc,c_user,c_router,c_has_read) values(?,?,?,?,?,?,?,?);";
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, sql, -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, , [[di deviceType] UTF8String], -, NULL);//绑定参数
sqlite3_bind_text(stmt, , [[di deviceUDN] UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [[di friendlyName] UTF8String], -, NULL);
sqlite3_bind_int(stmt, , (int)[di.time timeIntervalSince1970] );
sqlite3_bind_text(stmt, , [di.deviceDesc UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [account UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [routerjid UTF8String], -, NULL);
sqlite3_bind_int(stmt, , [di hasRead]);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
} }
- (NSMutableArray*)getHistoryRecordWithTHistoryRecordByUDN:(NSString* )UDN withAccount:(NSString* )account routerjid:(NSString *)routerjid
{
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
const char* sql = "select * from t_history_record where c_UDN = ? and c_user =? and c_router =? order by c_history_time desc";//查询语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, ,[UDN UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[account UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[routerjid UTF8String], -, NULL);
}else{
return nil;
}
NSMutableArray *dis=[[[NSMutableArray alloc]initWithCapacity:]autorelease];
while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
DescInfo* di = [[[DescInfo alloc]init]autorelease];
NSString* deviceType = nil;
NSString* friendlyName= nil;
NSString* deviceUDN= nil;
NSString* deviceDesc= nil;
NSDate* time= nil;
int c_id = ;
if (sqlite3_column_text(stmt, ) != NULL) {
c_id = sqlite3_column_int(stmt, ); }
if (sqlite3_column_text(stmt, ) != NULL) {
deviceType = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
if (sqlite3_column_text(stmt, ) != NULL) {
deviceUDN = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
if (sqlite3_column_text(stmt, ) != NULL) {
friendlyName = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
if (sqlite3_column_text(stmt, ) != NULL) {
int i = sqlite3_column_int(stmt, );
time = [NSDate dateWithTimeIntervalSince1970:i];
// time = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 4)];
}
if (sqlite3_column_text(stmt, ) != NULL) {
deviceDesc = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
di.deviceType=deviceType;
di.deviceUDN=deviceUDN;
di.friendlyName=friendlyName;
di.time = time;
di.deviceDesc =deviceDesc;
di.c_id = c_id;
[dis addObject:di];
} sqlite3_finalize(stmt);
sqlite3_close(db);
return dis ; }
- (NSMutableArray*)getHistoryRecordWithTHistoryRecordByAccount:(NSString* )account routerjid:(NSString *)routerjid
{
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
const char* sql = "select * from t_history_record where c_user = ? and c_router = ? order by c_history_time desc";//查询语句
sqlite3_stmt* stmt;
if (sqlite3_prepare_v2(db, sql, -, &stmt, nil)==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, ,[account UTF8String], -, NULL);
sqlite3_bind_text(stmt, ,[routerjid UTF8String], -, NULL);
}else{
return nil;
}
NSMutableArray *dis=[[[NSMutableArray alloc]initWithCapacity:]autorelease];
while ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
DescInfo* di = [[[DescInfo alloc]init]autorelease];
NSString* deviceType = nil;
NSString* friendlyName= nil;
NSString* deviceUDN= nil;
NSString* deviceDesc= nil;
NSDate* time= nil;
int c_id = ;
if (sqlite3_column_text(stmt, ) != NULL) {
c_id = sqlite3_column_int(stmt, ); }
if (sqlite3_column_text(stmt, ) != NULL) {
deviceType = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
if (sqlite3_column_text(stmt, ) != NULL) {
deviceUDN = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
if (sqlite3_column_text(stmt, ) != NULL) {
friendlyName = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
if (sqlite3_column_text(stmt, ) != NULL) {
int i = sqlite3_column_int(stmt, );
time = [NSDate dateWithTimeIntervalSince1970:i];
// time = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 4)];
}
if (sqlite3_column_text(stmt, ) != NULL) {
deviceDesc = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, )];
}
di.deviceType=deviceType;
di.deviceUDN=deviceUDN;
di.friendlyName=friendlyName;
di.time = time;
di.deviceDesc =deviceDesc;
di.c_id = c_id;
[dis addObject:di];
} sqlite3_finalize(stmt);
sqlite3_close(db);
return dis ; }
- (BOOL)deleteHistoryWithTHistoryRecordByDeviceType:(NSString *)deviceType account:(NSString* )account routerjid:(NSString *)routerjid
{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
return NO;
}
NSString* sql = [NSString stringWithFormat:@"delete from t_history_record where c_deviceType = ? and c_user = ? and c_router = ?"];
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, [sql UTF8String], -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, , [deviceType UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [account UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [routerjid UTF8String], -, NULL);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
}
}
- (BOOL)deleteHistoryWithTHistoryRecordById:(int)c_id account:(NSString* )account routerjid:(NSString *)routerjid {
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
return NO;
}
NSString* sql = [NSString stringWithFormat:@"delete from t_history_record where c_id = ? and c_user = ? and c_router = ?"];
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, [sql UTF8String], -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
// sqlite3_bind_text(stmt, 1, [c_id UTF8String], -1, NULL);
sqlite3_bind_int(stmt, , c_id);
sqlite3_bind_text(stmt, , [account UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [routerjid UTF8String], -, NULL);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
} } //update the count of history record not read
-(BOOL)updateHistoryCountNotReadWithHistoryRecordByDeviceType:(NSString *)deviceType account:(NSString* )account routerjid:(NSString *)routerjid
{
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
NSString * sql = [NSString stringWithFormat:@"update t_history_record set c_has_read = 1 where c_deviceType = ? and c_user = ? and c_router = ?"];//查询语句
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, [sql UTF8String], -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, , [deviceType UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [account UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [routerjid UTF8String], -, NULL);
}else{
return nil;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
}
} -(int)getHistoryCountNotReadWithHistoryRecordByAccount:(NSString *)account routerjid:(NSString *)routerjid
{
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String] , &db)){
return nil;
}
NSString * sql = [NSString stringWithFormat:@"select count (*) from t_history_record where c_has_read = 0 and c_user = ? and c_router = ?"];//查询语句
sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, [sql UTF8String], -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备
sqlite3_bind_text(stmt, , [account UTF8String], -, NULL);
sqlite3_bind_text(stmt, , [routerjid UTF8String], -, NULL);
}else{
return nil;
}
int count=;
if ( SQLITE_ROW == sqlite3_step(stmt) ){//执行
count=sqlite3_column_int(stmt, );
} sqlite3_finalize(stmt);
sqlite3_close(db);
return count ;
} #pragma mark manage normal tables
- (BOOL)deleteItemWithTable:(NSString*)table_ ByKey:(NSString*)key_ {
int ret = ;
if (SQLITE_OK != sqlite3_open([[self getFilePath] UTF8String], &db)){//打开数据库
return NO;
} NSString* sql= [NSString stringWithFormat:@"delete from %@ where c_account = ?",table_]; sqlite3_stmt* stmt;//
int result =sqlite3_prepare_v2(db, [sql UTF8String], -, &stmt, nil);
printf("%s\n",sqlite3_errmsg(db));
if (result==SQLITE_OK) {//准备语句
sqlite3_bind_text(stmt, , [key_ UTF8String], -, NULL);
}else{
return NO;
}
if (SQLITE_DONE == (ret = sqlite3_step(stmt))) {//执行查询
sqlite3_finalize(stmt);
sqlite3_close(db);
return YES;
}else{
return NO;
}
} @end

转:http://blog.csdn.net/kafeidev/article/details/17028423

分享一段ios数据库代码,包括对表的创建、升级、增删查改的更多相关文章

  1. Oracle数据库对表基本的操作--增删查改

    --向student表中加入入学时间属性,其数据类型为日期型alter table student add scome date; --删除student表中的入学时间属性alter table st ...

  2. mysql数据库,数据表,数据的增删查改语句

    查询mysql支持的引擎 show engines; 查询mysql支持的字符集 show character set; 设置mysql默认存储引擎 set default_storage_engin ...

  3. IOS CoreData的(增删查改)

    (1).CoreDataa>什么是CoreDatab>CoreData增删改查 "什么时候使用COredata 什么时候使用FMDatabases"CoreData 在 ...

  4. SQL Server 表的管理_关于数据增删查改的操作的详解(案例代码)

    SQL Server 表的管理_关于数据增删查改的操作的详解(案例代码)-DML 1.SQL INSERT INTO 语句(在表中插入) INSERT INTO 语句用于向表中插入新记录. SQL I ...

  5. java实现简单的数据库的增删查改,并布局交互界面

        一.系统简介 1.1.简介  本系统提供了学生信息管理中常见的基本功能,主要包括管理员.管理员的主要功能有对学生信息进行增加.删除.修改.查找等操作,对信息进行管理,对信息进行修改.查找等操作 ...

  6. Java连接MySQL数据库及简单的增删查改操作

    主要摘自 https://www.cnblogs.com/town123/p/8336244.html https://www.runoob.com/java/java-mysql-connect.h ...

  7. [课本]JDBC课程6--使用JDBC的DAO模块化--完成数据库的增删查改_工具类JDBCTools四个(Preparedstatement)功能模块的敲定版

    (课本P273-任务九) /**DAO: Data Access Object * 为什么用: 实现功能的模块化,更有利于代码的维护和升级 * 是什么: 访问数据信息的类,包含对数据的CRUD(cre ...

  8. SQL Server 表的管理_关于表的操作增删查改的操作的详解(案例代码)

    SQL Server 表的管理_关于表的操作增删查改的操作的详解(案例代码) 概述: 表由行和列组成,每个表都必须有个表名. SQL CREATE TABLE 语法 CREATE TABLE tabl ...

  9. MongoDB数据库(二):增删查改

    MongoDB数据库的增删查改 1.插入数据 语法: db.集合名称.insert(document) db.table_name.insert({name:'gj',gender:1}) db.ta ...

随机推荐

  1. 07 Go 1.7 Release Notes

    Go 1.7 Release Notes Introduction to Go 1.7 Changes to the language Ports Known Issues Tools Assembl ...

  2. 【Git使用详解】Egit的常用操作详解

    常用操作 操作 说明 Fetch 从远程获取最新版本到本地,不会自动merge Merge 可以把一个分支标签或某个commit的修改合并现在的分支上 Pull 从远程获取最新版本并merge到本地相 ...

  3. bootstrap fileinput插件使用感悟

    bootstrap fileinput 的填坑感悟              这个插件在demo的网站地址http://plugins.krajee.com/file-preview-icons-de ...

  4. Java编程的逻辑 (42) - 排序二叉树

    本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http:/ ...

  5. SOA并不能解决高并发事务

    传统SOA架构其实无法面对高并发事务. 这种方式不适合热点资源,也就是高并发场合. 虽然乐观锁短,但是容易产生脏数据. SOA是以服务这个方式对外提供功能,我们很显然喜欢在Service中加上JTA等 ...

  6. Kubernetes Master节点灾备恢复操作指南---升级版

    本文档简述了Kubernetes主节点灾备恢复的相关步骤,供在发生k8s master崩溃时操作. 就算是在k8s里部署了etcd群集, 主节点控制组件的高可用节点,灾备恢复也是必须要实现的操作,才能 ...

  7. 【LOJ】#2110. 「JLOI2015」管道连接

    题解 我们先跑一个斯坦纳树出来 斯坦纳树是什么,是一个包含点集里的点联通所需要的最小的价值,显然他们联通的方式必然是一棵树 我们可以设一个状态为\(dis[i][S]\)表示以第i个点为根,点集为\( ...

  8. error 1044 (42000):access denied for user ''@'localhost' to database 'quickapp' 解决方法

    在虚拟机上重新创建一个数据库时,一直出现这个报错:error 1044 (42000):access denied for user ''@'localhost' to database 'quick ...

  9. 【GO基础】main redeclared in this block问题的排查与解决

    之前的GO练习环境放在虚拟机内,方便了不少.不过在liteIDE打开的情况下,我迁移了虚拟机,刚好两台机子的VMware版本还不同,这就导致了无法恢复挂起状态,我放弃了挂起. 重新启动后,为了继续练习 ...

  10. AngularJS过滤器filter入门

    在开发中,经常会遇到这样的场景 如用户的性别分为“男”和“女”,在数据库中保存的值为1和0,用户在查看自己的性别时后端返回的值自然是1或0,前端要转换为“男”或“女”再显示出来: 如我要换个羽毛球拍, ...