1. main.m文件
#import <Foundation/Foundation.h>
#import "SQLManger.h"int main(int argc, const char * argv[]) {@autoreleasepool {NSLog(@"Hello, World!");SQLManger* sql = [SQLManger shareSqlManger];[sql createTable];[sql selectMessage];
[sql changeMessage];}return 0;
}
2. SQLManger.h 文件
#import <Foundation/Foundation.h>
#import <sqlite3.h>@interface SQLManger : NSObject
{sqlite3* db;
}
+(SQLManger*)shareSqlManger;
-(void)createTable;
-(void)selectMessage;
-(void)IncreaseMessage;
-(void)DeleteMessage;
-(void)changeMessage;
@end
3. SQLManger.m 文件
#import "SQLManger.h"
static SQLManger* sqlManger = nil;@implementation SQLManger
+(SQLManger*)shareSqlManger
{if (sqlManger == nil) {sqlManger = [[SQLManger alloc]init];}return sqlManger;
}
-(void)createTable
{
NSString* path = @"/Users/user/Downloads/数据库/nibaba.sqlite";if (sqlite3_open([path UTF8String], &db) == SQLITE_OK) {NSString* createTable=@"CREATE TABLE IF NOT EXISTS STUDENG (SID TEXT PRIMARY KEY,NAME TEXT);";char* error;if (sqlite3_exec(db, [createTable UTF8String], nil, nil, &error) == SQLITE_OK) {NSAssert(YES, @"数据表格创建成功%s", error);NSLog(@"数据表格创建成功");}else{NSAssert(NO, @"数据表格创建失败%s", error);NSLog(@"数据表格创建失败");}sqlite3_close(db);}}
-(void)selectMessage
{NSString* path = @"/Users/user/Downloads/数据库/nibaba.sqlite";if(sqlite3_open([path UTF8String], &db) == SQLITE_OK){NSString* selectSql = @"select *from areaCode where id=?";sqlite3_stmt* stmt;sqlite3_prepare_v2(db, [selectSql UTF8String], -1, &stmt, NULL);sqlite3_bind_int(stmt, 1, 10);if (sqlite3_step(stmt) == SQLITE_ROW) {NSLog(@" ====== %d", sqlite3_column_count(stmt));char* s = (char*)sqlite3_column_text(stmt, 1);NSLog(@" ------ %@",[NSString stringWithFormat:@"%s", s]);NSLog(@"------%d",sqlite3_column_int(stmt, 0));sqlite3_finalize(stmt);}else{sqlite3_finalize(stmt);sqlite3_close(db);}}else{sqlite3_close(db);}
}
-(void)IncreaseMessage
{NSString* path = @"/Users/user/Downloads/数据库/nibaba.sqlite";if(sqlite3_open([path UTF8String], &db) == SQLITE_OK){NSString *increase = @"insert into areaCode(id,location,countryCodeID) values (1,'镇魂街',02)";char* error;if (sqlite3_exec(db, [increase UTF8String], nil, nil, &error) == SQLITE_OK) {NSLog(@"增加数据表数据成功");}else{NSLog(@"增加数据表数据失败 == %s", error);}}
}
-(void)DeleteMessage
{NSString* path = @"/Users/user/Downloads/数据库/nibaba.sqlite";if(sqlite3_open([path UTF8String], &db) == SQLITE_OK){NSString *Delete = @"delete from areaCode where id = 1";char* error;if (sqlite3_exec(db, [Delete UTF8String], nil, nil, &error) == SQLITE_OK) {NSLog(@"删除数据表数据成功");}else{NSLog(@"删除数据表数据失败 == %s", error);}}
}
-(void)changeMessage
{NSString* path = @"/Users/user/Downloads/数据库/nibaba.sqlite";if(sqlite3_open([path UTF8String], &db) == SQLITE_OK){NSString *change = @"update areaCode set location = '镇魂街' WHERE id = 1";char* error;if (sqlite3_exec(db, [change UTF8String], nil, nil, &error) == SQLITE_OK) {NSLog(@"改变数据表数据成功");}else{NSLog(@"改变数据表数据失败 == %s", error);}}
}@end