// static的做用:能保證_db這個變量只被IWStudentTool.m直接訪問sql
static sqlite3 *_db;數據庫
+ (void)initialize數組
{spa
// 0.得到沙盒中的數據庫文件名3d
NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"];orm
// 1.建立(打開)數據庫(若是數據庫文件不存在,會自動建立)sqlite
int result = sqlite3_open(filename.UTF8String, &_db);rem
if (result == SQLITE_OK) {string
NSLog(@"成功打開數據庫");it
// 2.創表
const char *sql = "create table if not exists t_student (id integer primary key autoincrement, name text, age integer);";
char *errorMesg = NULL;
int result = sqlite3_exec(_db, sql, NULL, NULL, &errorMesg);
if (result == SQLITE_OK) {
NSLog(@"成功建立t_student表");
} else {
NSLog(@"建立t_student表失敗:%s", errorMesg);
}
} else {
NSLog(@"打開數據庫失敗");
}
}
+ (BOOL)addStudent:(IWStudent *)student
{
NSString *sql = [NSString stringWithFormat:@"insert into t_student (name, age) values('%@', %d);", student.name, student.age];
char *errorMesg = NULL;
int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errorMesg);
return result == SQLITE_OK;
}
+ (NSArray *)students
{
// 0.定義數組
NSMutableArray *students = nil;
// 1.定義sql語句
const char *sql = "select id, name, age from t_student;";
// 2.定義一個stmt存放結果集
sqlite3_stmt *stmt = NULL;
// 3.檢測SQL語句的合法性
int result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL);
if (result == SQLITE_OK) {
NSLog(@"查詢語句是合法的");
students = [NSMutableArray array];
// 4.執行SQL語句,從結果集中取出數據
while (sqlite3_step(stmt) == SQLITE_ROW) { // 真的查詢到一行數據
// 得到這行對應的數據
IWStudent *student = [[IWStudent alloc] init];
// 得到第0列的id
student.ID = sqlite3_column_int(stmt, 0);
// 得到第1列的name
const unsigned char *sname = sqlite3_column_text(stmt, 1);
student.name = [NSString stringWithUTF8String:(const char *)sname];
// 得到第2列的age
student.age = sqlite3_column_int(stmt, 2);
// 添加到數組
[students addObject:student];
}
} else {
NSLog(@"查詢語句非合法");
}
return students;
}
+ (NSArray *)studentsWithCondition:(NSString *)condition
{
// 0.定義數組
NSMutableArray *students = nil;
// 1.定義sql語句
const char *sql = "select id, name, age from t_student where name like ?;";
// 2.定義一個stmt存放結果集
sqlite3_stmt *stmt = NULL;
// 3.檢測SQL語句的合法性
int result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL);
if (result == SQLITE_OK) {
NSLog(@"查詢語句是合法的");
students = [NSMutableArray array];
// 填補佔位符的內容
NSString *newCondition = [NSString stringWithFormat:@"%%%@%%", condition];
// NSLog(@"%@", newCondition);
sqlite3_bind_text(stmt, 1, newCondition.UTF8String, -1, NULL);
// 4.執行SQL語句,從結果集中取出數據
while (sqlite3_step(stmt) == SQLITE_ROW) { // 真的查詢到一行數據
// 得到這行對應的數據
IWStudent *student = [[IWStudent alloc] init];
// 得到第0列的id
student.ID = sqlite3_column_int(stmt, 0);
// 得到第1列的name
const unsigned char *sname = sqlite3_column_text(stmt, 1);
student.name = [NSString stringWithUTF8String:(const char *)sname];
// 得到第2列的age
student.age = sqlite3_column_int(stmt, 2);
// 添加到數組
[students addObject:student];
}
} else {
NSLog(@"查詢語句非合法");
}
return students;
}