操作數(shù)據(jù)庫

#import<Foundation/Foundation.h>

#import<sqlite3.h>

#import "sqlTestList.h"

#define kFilename? @"testdb.db"

@class sqlTestList;

@interface sqlService : NSObject

{

sqlite3 *_database;

}

@property (nonatomic) sqlite3 *_database;

-(BOOL) createTestList:(sqlite3 *)db;//創(chuàng)建數(shù)據(jù)庫

-(BOOL) insertTestList:(sqlTestList *)insertList;//插入數(shù)據(jù)

-(BOOL) updateTestList:(sqlTestList *)updateList;//更新數(shù)據(jù)

-(NSMutableArray*)getTestList;//獲取全部數(shù)據(jù)

- (BOOL) deleteTestList:(sqlTestList *)deletList;//刪除數(shù)據(jù):

- (NSMutableArray*)searchTestList:(NSString*)searchString;//查詢數(shù)據(jù)庫,searchID為要查詢數(shù)據(jù)的ID,返回?cái)?shù)據(jù)為查詢到的數(shù)據(jù)

@end


//

//? sqlService.m

//? 操作數(shù)據(jù)庫

//

//

#import "sqlService.h"

@implementation sqlService

@synthesize _database;

- (id)init

{

return self;

}

//獲取document目錄并返回?cái)?shù)據(jù)庫目錄

- (NSString *)dataFilePath{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSLog(@"=======%@",documentsDirectory);

return [documentsDirectory stringByAppendingPathComponent:@"data.db"];//這里很神奇,可以定義成任何類型的文件,也可以不定義成.db文件,任何格式都行,定義成.sb文件都行,達(dá)到了很好的數(shù)據(jù)隱秘性

}

//創(chuàng)建,打開數(shù)據(jù)庫

- (BOOL)openDB {

//獲取數(shù)據(jù)庫路徑

NSString *path = [self dataFilePath];

//文件管理器

NSFileManager *fileManager = [NSFileManager defaultManager];

//判斷數(shù)據(jù)庫是否存在

BOOL find = [fileManager fileExistsAtPath:path];

//如果數(shù)據(jù)庫存在,則用sqlite3_open直接打開(不要擔(dān)心,如果數(shù)據(jù)庫不存在sqlite3_open會(huì)自動(dòng)創(chuàng)建)

if (find) {

NSLog(@"Database file have already existed.");

//打開數(shù)據(jù)庫,這里的[path UTF8String]是將NSString轉(zhuǎn)換為C字符串,因?yàn)镾QLite3是采用可移植的C(而不是

//Objective-C)編寫的,它不知道什么是NSString.

if(sqlite3_open([path UTF8String], &_database) != SQLITE_OK) {

//如果打開數(shù)據(jù)庫失敗則關(guān)閉數(shù)據(jù)庫

sqlite3_close(self._database);

NSLog(@"Error: open database file.");

return NO;

}

//創(chuàng)建一個(gè)新表

[self createTestList:self._database];

return YES;

}

//如果發(fā)現(xiàn)數(shù)據(jù)庫不存在則利用sqlite3_open創(chuàng)建數(shù)據(jù)庫(上面已經(jīng)提到過),與上面相同,路徑要轉(zhuǎn)換為C字符串

if(sqlite3_open([path UTF8String], &_database) == SQLITE_OK) {

//創(chuàng)建一個(gè)新表

[self createTestList:self._database];

return YES;

} else {

//如果創(chuàng)建并打開數(shù)據(jù)庫失敗則關(guān)閉數(shù)據(jù)庫

sqlite3_close(self._database);

NSLog(@"Error: open database file.");

return NO;

}

return NO;

}

//創(chuàng)建表

- (BOOL) createTestList:(sqlite3*)db {

//這句是大家熟悉的SQL語句

char *sql = "create table if not exists testTable(ID INTEGER PRIMARY KEY AUTOINCREMENT, testID int,testValue text,testName text)";// testID是列名,int 是數(shù)據(jù)類型,testValue是列名,text是數(shù)據(jù)類型,是字符串類型

sqlite3_stmt *statement;

//sqlite3_prepare_v2 接口把一條SQL語句解析到statement結(jié)構(gòu)里去. 使用該接口訪問數(shù)據(jù)庫是當(dāng)前比較好的的一種方法

NSInteger sqlReturn = sqlite3_prepare_v2(_database, sql, -1, &statement, nil);

//第一個(gè)參數(shù)跟前面一樣,是個(gè)sqlite3 * 類型變量,

//第二個(gè)參數(shù)是一個(gè) sql 語句。

//第三個(gè)參數(shù)我寫的是-1,這個(gè)參數(shù)含義是前面 sql 語句的長度。如果小于0,sqlite會(huì)自動(dòng)計(jì)算它的長度(把sql語句當(dāng)成以\0結(jié)尾的字符串)。

//第四個(gè)參數(shù)是sqlite3_stmt 的指針的指針。解析以后的sql語句就放在這個(gè)結(jié)構(gòu)里。

//第五個(gè)參數(shù)是錯(cuò)誤信息提示,一般不用,為nil就可以了。

//如果這個(gè)函數(shù)執(zhí)行成功(返回值是 SQLITE_OK 且 statement 不為NULL ),那么下面就可以開始插入二進(jìn)制數(shù)據(jù)。

//如果SQL語句解析出錯(cuò)的話程序返回

if(sqlReturn != SQLITE_OK) {

NSLog(@"Error: failed to prepare statement:create test table");

return NO;

}

//執(zhí)行SQL語句

int success = sqlite3_step(statement);

//釋放sqlite3_stmt

sqlite3_finalize(statement);

//執(zhí)行SQL語句失敗

if ( success != SQLITE_DONE) {

NSLog(@"Error: failed to dehydrate:create table test");

return NO;

}

NSLog(@"Create table 'testTable' successed.");

return YES;

}

//插入數(shù)據(jù)

-(BOOL) insertTestList:(sqlTestList *)insertList {

//先判斷數(shù)據(jù)庫是否打開

if ([self openDB]) {

sqlite3_stmt *statement;

//這個(gè) sql 語句特別之處在于 values 里面有個(gè)? 號(hào)。在sqlite3_prepare函數(shù)里,?號(hào)表示一個(gè)未定的值,它的值等下才插入。

static char *sql = "INSERT INTO testTable(testID, testValue,testName) VALUES(?, ?, ?)";

int success2 = sqlite3_prepare_v2(_database, sql, -1, &statement, NULL);

if (success2 != SQLITE_OK) {

NSLog(@"Error: failed to insert:testTable");

sqlite3_close(_database);

return NO;

}

//這里的數(shù)字1,2,3代表上面的第幾個(gè)問號(hào),這里將三個(gè)值綁定到三個(gè)綁定變量

sqlite3_bind_int(statement, 1, insertList.stuid);

sqlite3_bind_text(statement, 2, [insertList.stupwd UTF8String], -1, SQLITE_TRANSIENT);

sqlite3_bind_text(statement, 3, [insertList.stuname UTF8String], -1, SQLITE_TRANSIENT);

//執(zhí)行插入語句

success2 = sqlite3_step(statement);

//釋放statement

sqlite3_finalize(statement);

//如果插入失敗

if (success2 == SQLITE_ERROR) {

NSLog(@"Error: failed to insert into the database with message.");

//關(guān)閉數(shù)據(jù)庫

sqlite3_close(_database);

return NO;

}

//關(guān)閉數(shù)據(jù)庫

sqlite3_close(_database);

return YES;

}

return NO;

}

//獲取數(shù)據(jù)

- (NSMutableArray*)getTestList{

NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];

//判斷數(shù)據(jù)庫是否打開

if ([self openDB]) {

sqlite3_stmt *statement = nil;

//sql語句

char *sql = "SELECT testID, testValue ,testName FROM testTable";//從testTable這個(gè)表中獲取 testID, testValue ,testName,若獲取全部的話可以用*代替testID, testValue ,testName。

if (sqlite3_prepare_v2(_database, sql, -1, &statement, NULL) != SQLITE_OK) {

NSLog(@"Error: failed to prepare statement with message:get testValue.");

return NO;

}

else {

//查詢結(jié)果集中一條一條的遍歷所有的記錄,這里的數(shù)字對(duì)應(yīng)的是列值,注意這里的列值,跟上面sqlite3_bind_text綁定的列值不一樣!一定要分開,不然會(huì)crash,只有這一處的列號(hào)不同,注意!

while (sqlite3_step(statement) == SQLITE_ROW) {

sqlTestList* sqlList = [[sqlTestList alloc] init] ;

sqlList.stuid? ? = sqlite3_column_int(statement,0);

char* strText? = (char*)sqlite3_column_text(statement, 1);

sqlList.stupwd = [NSString stringWithUTF8String:strText];

char *strName = (char*)sqlite3_column_text(statement, 2);

sqlList.stuname = [NSString stringWithUTF8String:strName];

[array addObject:sqlList];

}

}

sqlite3_finalize(statement);

sqlite3_close(_database);

}

return array;//定義了自動(dòng)釋放的NSArray,這樣不是個(gè)好辦法,會(huì)造成內(nèi)存泄露,建議大家定義局部的數(shù)組,再賦給屬性變量。

}

//更新數(shù)據(jù)

-(BOOL) updateTestList:(sqlTestList *)updateList{

if ([self openDB]) {

sqlite3_stmt *statement;//這相當(dāng)一個(gè)容器,放轉(zhuǎn)化OK的sql語句

//組織SQL語句

char *sql = "update testTable set testValue = ? and testName = ? WHERE testID = ?";

//將SQL語句放入sqlite3_stmt中

int success = sqlite3_prepare_v2(_database, sql, -1, &statement, NULL);

if (success != SQLITE_OK) {

NSLog(@"Error: failed to update:testTable");

sqlite3_close(_database);

return NO;

}

//這里的數(shù)字1,2,3代表第幾個(gè)問號(hào)。這里只有1個(gè)問號(hào),這是一個(gè)相對(duì)比較簡(jiǎn)單的數(shù)據(jù)庫操作,真正的項(xiàng)目中會(huì)遠(yuǎn)遠(yuǎn)比這個(gè)復(fù)雜

//綁定text類型的數(shù)據(jù)庫數(shù)據(jù)

sqlite3_bind_text(statement, 3, [updateList.stuname UTF8String], -1, SQLITE_TRANSIENT);

sqlite3_bind_text(statement, 2, [updateList.stupwd UTF8String], -1, SQLITE_TRANSIENT);

sqlite3_bind_int(statement, 1, updateList.stuid);

//執(zhí)行SQL語句。這里是更新數(shù)據(jù)庫

success = sqlite3_step(statement);

//釋放statement

sqlite3_finalize(statement);

//如果執(zhí)行失敗

if (success == SQLITE_ERROR) {

NSLog(@"Error: failed to update the database with message.");

//關(guān)閉數(shù)據(jù)庫

sqlite3_close(_database);

return NO;

}

//執(zhí)行成功后依然要關(guān)閉數(shù)據(jù)庫

sqlite3_close(_database);

return YES;

}

return NO;

}

//刪除數(shù)據(jù)

- (BOOL) deleteTestList:(sqlTestList *)deletList{

if ([self openDB]) {

sqlite3_stmt *statement;

//組織SQL語句

static char *sql = "delete from testTable? where testID = ? and testValue = ? and testName = ?";

//將SQL語句放入sqlite3_stmt中

int success = sqlite3_prepare_v2(_database, sql, -1, &statement, NULL);

if (success != SQLITE_OK) {

NSLog(@"Error: failed to delete:testTable");

sqlite3_close(_database);

return NO;

}

//這里的數(shù)字1,2,3代表第幾個(gè)問號(hào)。這里只有1個(gè)問號(hào),這是一個(gè)相對(duì)比較簡(jiǎn)單的數(shù)據(jù)庫操作,真正的項(xiàng)目中會(huì)遠(yuǎn)遠(yuǎn)比這個(gè)復(fù)雜

sqlite3_bind_int(statement, 1, deletList.stuid);

sqlite3_bind_text(statement, 2, [deletList.stupwd UTF8String], -1, SQLITE_TRANSIENT);

sqlite3_bind_text(statement, 3, [deletList.stuname UTF8String], -1, SQLITE_TRANSIENT);

//執(zhí)行SQL語句。這里是更新數(shù)據(jù)庫

success = sqlite3_step(statement);

//釋放statement

sqlite3_finalize(statement);

//如果執(zhí)行失敗

if (success == SQLITE_ERROR) {

NSLog(@"Error: failed to delete the database with message.");

//關(guān)閉數(shù)據(jù)庫

sqlite3_close(_database);

return NO;

}

//執(zhí)行成功后依然要關(guān)閉數(shù)據(jù)庫

sqlite3_close(_database);

return YES;

}

return NO;

}

//查詢數(shù)據(jù)

- (NSMutableArray*)searchTestList:(NSString*)searchString{

NSMutableArray *array = [NSMutableArray arrayWithCapacity:10];

//判斷數(shù)據(jù)庫是否打開

if ([self openDB]) {

sqlite3_stmt *statement = nil;

//sql語句

NSString *querySQL = [NSString stringWithFormat:@"SELECT * from testTable where testName like \"%@\"",searchString];

const char *sql = [querySQL UTF8String];

//? ? ? ? char *sql = "SELECT * FROM testTable WHERE testName like ?";//這里用like代替=可以執(zhí)行模糊查找,原來是"SELECT * FROM testTable WHERE testName = ?"

if (sqlite3_prepare_v2(_database, sql, -1, &statement, NULL) != SQLITE_OK) {

NSLog(@"Error: failed to prepare statement with message:search testValue.");

return NO;

} else {

sqlTestList *searchList = [[sqlTestList alloc]init];

//? ? ? ? ? ? sqlite3_bind_int(statement, 1, searchID);

sqlite3_bind_text(statement, 3, [searchString UTF8String], -1, SQLITE_TRANSIENT);

//查詢結(jié)果集中一條一條的遍歷所有的記錄,這里的數(shù)字對(duì)應(yīng)的是列值。

while (sqlite3_step(statement) == SQLITE_ROW) {

sqlTestList* sqlList = [[sqlTestList alloc] init] ;

sqlList.stuid? = sqlite3_column_int(statement,1);

char* strText? = (char*)sqlite3_column_text(statement, 2);

sqlList.stupwd = [NSString stringWithUTF8String:strText];

char *strName = (char*)sqlite3_column_text(statement, 3);

sqlList.stuname = [NSString stringWithUTF8String:strName];

[array addObject:sqlList];

}

}

sqlite3_finalize(statement);

sqlite3_close(_database);

}

return array;

}

@end


#import<Foundation/Foundation.h>

#import<sqlite3.h>

@interface sqlTestList : NSObject//重新定義了一個(gè)類,專門用于存儲(chǔ)數(shù)據(jù)

{

int sqlID;

NSString *sqlText;

NSString *sqlname;

}

@property (nonatomic) int stuid;

@property (nonatomic, retain) NSString *stupwd;

@property (nonatomic, retain) NSString *stuname;

@end

#import "sqlTestList.h"

@implementation sqlTestList

@synthesize stuid;

@synthesize stupwd;

@synthesize stuname;

-(id) init

{

stuid = 0;

stupwd = @"";

stuname = @"";

return self;

};

@end


#import<UIKit/UIKit.h>

#import "sqlService.h"

@interface operateSqlViewController : UIViewController

{

UITextField *idValue;

UITextField *textValue;

UITextField *textName;

int oprateType;//區(qū)分?jǐn)?shù)據(jù)插入與更新

sqlTestList *sqlValue;

}

@property (nonatomic, retain) UITextField *idValue;

@property (nonatomic, retain) UITextField *textValue;

@property (nonatomic, retain) UITextField *textName;

@property (nonatomic, retain) sqlTestList *sqlValue;

@property (nonatomic) int oprateType;

@end

#import "operateSqlViewController.h"

@interface operateSqlViewController ()

@end

@implementation operateSqlViewController

@synthesize idValue;

@synthesize textValue;

@synthesize oprateType;

@synthesize sqlValue;

@synthesize textName;

- (void)viewDidLoad {

[super viewDidLoad];

UIBarButtonItem *backButton = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(dismiss:)];

UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]

initWithTitle:@"保存" style: UIBarButtonItemStyleBordered target:self action:@selector(saveValue:)];

[[self navigationItem] setLeftBarButtonItem:backButton];

[[self navigationItem] setRightBarButtonItem:saveButton];

if (oprateType == 0) {

[self.navigationItem setTitle:@"數(shù)據(jù)插入"];

}

else if(oprateType == 1){

[self.navigationItem setTitle:@"數(shù)據(jù)更新"];

idValue.text = [NSString stringWithFormat:@"%d", sqlValue.stuid];

textValue.text = sqlValue.stuname;

textName.text = sqlValue.stuname;

}

}

- (void)dismiss:(id)sender{

[[self parentViewController] dismissModalViewControllerAnimated:YES];

}

- (void)saveValue:(id)sender{

if (idValue.text.length == 0) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"請(qǐng)輸入ID"

delegate:self

cancelButtonTitle:@"好"

otherButtonTitles:nil];

[alert show];

return;

}

if (textValue.text.length == 0) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"請(qǐng)輸入電話"

delegate:self

cancelButtonTitle:@"好"

otherButtonTitles:nil];

[alert show];

return;

}

if (textName.text.length == 0) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"請(qǐng)輸入姓名"

delegate:self

cancelButtonTitle:@"好"

otherButtonTitles:nil];

[alert show];

return;

}

//初始化數(shù)據(jù)庫

sqlService *sqlSer = [[sqlService alloc] init];

//數(shù)據(jù)庫插入

if (oprateType == 0) {

sqlTestList *sqlInsert = [[sqlTestList alloc]init];

sqlInsert.stuid = [idValue.text intValue];

sqlInsert.stupwd = textValue.text;

sqlInsert.stuname = textName.text;

//調(diào)用封裝好的數(shù)據(jù)庫插入函數(shù)

if ([sqlSer insertTestList:sqlInsert]) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"插入數(shù)據(jù)成功"delegate:self cancelButtonTitle:@"好"otherButtonTitles:nil];

[alert show];

}

else {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"插入數(shù)據(jù)失敗"delegate:self cancelButtonTitle:@"好"otherButtonTitles:nil];

[alert show];

}

}

//數(shù)據(jù)庫更新

if(oprateType == 1){

sqlTestList *newValue = [[sqlTestList alloc]init];

newValue.stuid = [idValue.text intValue];

newValue.stupwd = textValue.text;

newValue.stuname = textName.text;

//調(diào)用封裝好的更新數(shù)據(jù)庫函數(shù)

if ([sqlSer updateTestList:newValue]) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"更新數(shù)據(jù)成功"delegate:self cancelButtonTitle:@"好"otherButtonTitles:nil];

[alert show];

}

else {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"更新數(shù)據(jù)失敗"delegate:self cancelButtonTitle:@"好"otherButtonTitles:nil];

[alert show];

}

}

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end


#import<UIKit/UIKit.h>

#import "sqlService.h"@interface SQLite3TestViewController : UIViewController{

UITableView *utableView;

NSArray *listData;

UISearchBar *searchBar;//搜索欄

}

@property (nonatomic, retain) UITableView *utableView;

@property (nonatomic, retain) UISearchBar *searchBar;

@property (nonatomic, retain) NSArray *listData;

- (void)insertValue;

- (void)updateValue;

- (void)getAllValue;

- (void)deleteValue;

- (void)searchValue;

@end

#import "SQLite3TestViewController.h"

#import "operateSqlViewController.h"

@interface SQLite3TestViewController ()

@end

@implementation SQLite3TestViewController

@synthesize utableView;

@synthesize listData;

@synthesize searchBar;

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view.

sqlService *sqlSer = [[sqlService alloc] init];

listData = [sqlSer getTestList];//先初始化那個(gè)專門用于存數(shù)據(jù)的類,才調(diào)用類獲取數(shù)據(jù)的方法

self.utableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];

self.utableView.backgroundColor = [UIColor colorWithRed:0.879 green:1.000 blue:0.467 alpha:1.000];

self.utableView.delegate = self;

self.utableView.dataSource = self;

[self.view addSubview:self.utableView];

}

- (void)viewDidAppear:(BOOL)animated{//在這里寫是為了等待時(shí)間縮短一點(diǎn),數(shù)據(jù)如果很多的,在這里寫可以讓數(shù)據(jù)提前加載

sqlService *sqlSer = [[sqlService alloc] init];

listData = [sqlSer getTestList];

[utableView reloadData];

}

- (void)viewDidUnload {

utableView = nil;

listData = nil;

searchBar = nil;

[super viewDidUnload];

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}

- (void)insertValue{

[searchBar resignFirstResponder];//觸發(fā)這個(gè)insertValue方法時(shí)隱藏鍵盤

operateSqlViewController *operateController = [[operateSqlViewController alloc] init ];

UINavigationController *theNavController = [[UINavigationController alloc]

initWithRootViewController:operateController];//這里如果不初始化一個(gè)UINavigationController類的對(duì)象來存放operateSqlViewController類的UIViewController,就不會(huì)有最上面的導(dǎo)航欄了。

operateController.oprateType = 0;//optrateType為0時(shí)為數(shù)據(jù)插入

theNavController.navigationBar.tintColor = [UIColor blackColor];

[self presentModalViewController:theNavController animated:YES];

}

- (void)updateValue{

[searchBar resignFirstResponder];

NSIndexPath *indexPath = [utableView? indexPathForSelectedRow];

if (indexPath == nil) {

//UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"message:@"請(qǐng)選擇要更新的項(xiàng)" delegate:selfcancelButtonTitle:@"好" otherButtonTitles:nil];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"請(qǐng)選擇要更新的項(xiàng)" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil, nil];

[alert show];

}

NSUInteger row = [indexPath row];

sqlTestList *sqlList = [[sqlTestList alloc]init];

sqlList = [listData objectAtIndex:(row - 1)];//在這里面獲取點(diǎn)擊的行,因?yàn)閠able的第一行沒顯示數(shù)據(jù),所以這里要減1。

operateSqlViewController *operateController = [[operateSqlViewController alloc] init ];

UINavigationController *theNavController = [[UINavigationController alloc]

initWithRootViewController:operateController];

operateController.oprateType = 1;//optrateType為1時(shí)為數(shù)據(jù)更新

operateController.sqlValue = sqlList;

theNavController.navigationBar.tintColor = [UIColor blackColor];

[self presentModalViewController:theNavController animated:YES];

}

- (void)getAllValue{

[searchBar resignFirstResponder];

sqlService *sqlSer = [[sqlService alloc] init];

listData = [sqlSer getTestList];

[utableView reloadData];

}

- (void)deleteValue{

[searchBar resignFirstResponder];

NSIndexPath *indexPath = [utableView? indexPathForSelectedRow];

if (indexPath == nil) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"請(qǐng)選擇要?jiǎng)h除的項(xiàng)"

delegate:self

cancelButtonTitle:@"好"

otherButtonTitles:nil];

[alert show];

}

NSUInteger row = [indexPath row];

sqlTestList *sqlList = [[sqlTestList alloc]init];

sqlList = [listData objectAtIndex:(row - 1)];

sqlService *sqlSer = [[sqlService alloc] init];

if ([sqlSer deleteTestList:sqlList]) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"刪除數(shù)據(jù)成功"

delegate:self

cancelButtonTitle:@"好"

otherButtonTitles:nil];

[alert show];

//刪除成功后重新獲取數(shù)據(jù)更新列表

listData = [sqlSer getTestList];

[utableView reloadData];

}

else {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"刪除數(shù)據(jù)失敗"

delegate:self

cancelButtonTitle:@"好"

otherButtonTitles:nil];

[alert show];

}

}

- (void)searchValue{

if ([searchBar.text isEqualToString:@""]) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"請(qǐng)輸入要查詢數(shù)據(jù)的ID"

delegate:self

cancelButtonTitle:@"好"

otherButtonTitles:nil];

[alert show];

}

else {

//? ? ? ? int idNum = [searchBar.text intValue];

NSString *str = searchBar.text;

sqlService *sqlSer = [[sqlService alloc] init];

listData = [sqlSer searchTestList:str];

if ([listData? count] == 0) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"

message:@"sorry,未查詢到數(shù)據(jù),請(qǐng)查看name是否有誤"

delegate:self

cancelButtonTitle:@"好"

otherButtonTitles:nil];

[alert show];

}

[searchBar resignFirstResponder];

[utableView reloadData];

}

}

#pragma mark -

#pragma mark Table View Data Source Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

// Return the number of rows in the section.

return [listData count] + 1;//從第二行開始,第一行不顯示數(shù)據(jù)

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

NSString *CustomIdentifier =? [NSString stringWithFormat:@"cell%ld",(long)indexPath.row];

//cell不重用

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CustomIdentifier];

if (indexPath.row == 0)

cell.selectionStyle = UITableViewCellSelectionStyleNone;

if ( cell == nil ) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CustomIdentifier];

cell.backgroundColor = [UIColor clearColor];

}

if (indexPath.row > 0)

{

NSUInteger row = [indexPath row];

sqlTestList *sqlList = [[sqlTestList alloc] init] ;

if (listData != nil)

sqlList = [listData objectAtIndex: (row - 1)];//讀取數(shù)據(jù)的時(shí)候也要減一行,從第二行開始

UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0+40, 10, 70, 30)];

UILabel *IDLabel = [[UILabel alloc]initWithFrame:CGRectMake(90+40, 10, 70, 30)];

UILabel *valueLabel = [[UILabel alloc]initWithFrame:CGRectMake(180+40, 10, 70, 30)];

nameLabel.text = sqlList.stuname;

IDLabel.text = sqlList.stupwd;

valueLabel.text = [NSString stringWithFormat:@"%d",sqlList.stuid];

[cell.contentView addSubview:nameLabel];

[cell.contentView addSubview:IDLabel];

[cell.contentView addSubview:valueLabel];

}

else

{

for (int i = 0; i < 3; i ++) {

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(90 * i + 40, 10, 70 , 30)];

NSArray *array = [NSArray arrayWithObjects:@"姓名",@"ID",@"電話", nil];

label.text = [array objectAtIndex:i];

label.backgroundColor = [UIColor clearColor];

[cell.contentView addSubview:label];

}

}

return cell;

}

- (NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

[searchBar resignFirstResponder];

if (indexPath.row == 0) {

return nil;//讓第一行不能點(diǎn)擊

}

else

return indexPath;

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

/*

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

// Get the new view controller using [segue destinationViewController].

// Pass the selected object to the new view controller.

}

*/

@end


#import<UIKit/UIKit.h>

#import "SQLite3TestViewController.h"@interface AppDelegate : UIResponder@property (strong, nonatomic) UIWindow *window;

@end

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Override point for customization after application launch.

self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[[SQLite3TestViewController alloc] init]];

return YES;

}

- (void)applicationWillResignActive:(UIApplication *)application {

// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}

- (void)applicationDidEnterBackground:(UIApplication *)application {

// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

}

- (void)applicationWillEnterForeground:(UIApplication *)application {

// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

}

- (void)applicationDidBecomeActive:(UIApplication *)application {

// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}

- (void)applicationWillTerminate:(UIApplication *)application {

// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

}

@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容