iOS_資料庫3_sqlite3基本操作,ios3_sqlite3
最終:
Sqlite3函數總結
1.開啟資料庫int sqlite3_open( const char *filename, // 資料庫的檔案路徑 sqlite3 **ppDb // 資料庫執行個體);2.執行任何SQL語句int sqlite3_exec( sqlite3*, // 一個開啟的資料庫執行個體 const char *sql, // 需要執行的SQL語句 int (*callback)(void*,int,char**,char**), // SQL語句執行完畢後的回調 void *, // 回呼函數的第1個參數 char **errmsg // 錯誤資訊);3.檢查SQL語句的合法性(查詢前的準備)int sqlite3_prepare_v2( sqlite3 *db, // 資料庫執行個體 const char *zSql, // 需要檢查的SQL語句 int nByte, // SQL語句的最大位元組長度 sqlite3_stmt **ppStmt, // sqlite3_stmt執行個體,用來獲得資料庫資料 const char **pzTail);4.查詢一行資料int sqlite3_step(sqlite3_stmt*); // 如果查詢到一行資料,就會返回SQLITE_ROW5.利用stmt獲得某一欄位的值(欄位的下標從0開始)double sqlite3_column_double(sqlite3_stmt*, int iCol); // 浮點數據int sqlite3_column_int(sqlite3_stmt*, int iCol); // 整型資料sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); // 長整型資料const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); // 二進位文本資料const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); // 字串資料
控制器中直接寫SQL語句,未封裝
//// ViewController.m// 1.sqlite3基本操作//// Created by xss on 14-11-2.// Copyright (c) 2014年 beyond. All rights reserved.//#import "ViewController.h"// 1.匯入庫,2.添加主標頭檔#import <sqlite3.h>@interface ViewController (){ // db代表著整個資料庫,db是資料庫執行個體 sqlite3 *_db;}@end@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; // 0.獲得沙箱中的資料庫檔案名 NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"]; NSLog(@"filePath:%@",filename); /* 2014-11-02 18:32:38.895 1.sqlite3基本操作[85356:245858] filePath:/Users/juns/Library/Developer/CoreSimulator/Devices/3198E002-E3C9-4523-983E-AC3E1283A654/data/Containers/Data/Application/E1150608-3EB8-4B9D-87AF-33EDF9FB6FF3/Documents/student.sqlite 2014-11-02 18:32:38.896 1.sqlite3基本操作[85356:245858] 成功開啟資料庫 2014-11-02 18:32:38.897 1.sqlite3基本操作[85356:245858] 成功建立t_student表 */ // 1.建立(開啟)資料庫(如果是首次開啟,則資料庫檔案不存在,那麼會自動建立) // OC字串,直接轉成C語言字串,通過 UTF8String方法 int result = sqlite3_open(filename.UTF8String, &_db); if (result == SQLITE_OK) { NSLog(@"成功開啟資料庫"); // 2.創表 const char *sql = "create table if not exists t_student (id integer primary key autoincrement, name text, age integer);"; // 凡是要傳地址的,最好先清空,防止出現野指標,C語言中空是NULL char *errorMesg = NULL; // 參數3和4是回調時用 int result = sqlite3_exec(_db, sql, NULL, NULL, &errorMesg); if (result == SQLITE_OK) { NSLog(@"成功建立t_student表"); } else { NSLog(@"建立t_student表失敗:%s", errorMesg); } } else { NSLog(@"開啟資料庫失敗"); }}// 完全仿造createTable操作- (IBAction)insertBtnClicked:(UIButton *)sender{ for (int i = 0; i<30; i++) { NSString *name = [NSString stringWithFormat:@"beyond-%d", arc4random()%100]; int age = arc4random()%100; NSString *sql = [NSString stringWithFormat:@"insert into t_student (name, age) values('%@', %d);", name, age]; char *errorMesg = NULL; int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errorMesg); if (result == SQLITE_OK) { NSLog(@"成功添加資料"); } else { NSLog(@"添加資料失敗:%s", errorMesg); } }}// 方法同上- (IBAction)deleteBtnClicked:(UIButton *)sender{}// 方法同上- (IBAction)updateBtnClicked:(UIButton *)sender{}//- (IBAction)queryBtnClicked:(UIButton *)sender{ // SQL注入漏洞 /** 登入功能 1.使用者輸入帳號和密碼 * 帳號:123' or 1 = 1 or '' = ' * 密碼:456654679 2.拿到使用者輸入的帳號和密碼去資料庫查詢(查詢有沒有這個使用者名稱和密碼) select * from t_user where username = '123' and password = '456'; select * from t_user where username = '123' and password = '456'; */ // 1.定義sql語句 const char *sql = "select id, name, age from t_student where name = ?;"; // 2.定義一個stmt存放結果集,用於執行靜態 SQL 陳述式並返回它所產生結果的對象 sqlite3_stmt *stmt = NULL; // 3.檢測SQL語句的合法性,參數3是sql語句的長度,只要寫-1,會自動計算,參數4是statement存放結果集 int result = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL); if (result == SQLITE_OK) { NSLog(@"查詢語句是合法的"); // 設定預留位置的內容,參數2 指的是第幾個預留位置號,注意是從1開始;參數4是預留位置的長度,只要寫-1,會自動計算, sqlite3_bind_text(stmt, 1, "beyond", -1, NULL); // 4.step 執行SQL語句,從結果集中取出資料 // int stepResult = sqlite3_step(stmt); // step的執行結果等於SQLITE_ROW,表示真的查詢到一行資料 while (sqlite3_step(stmt) == SQLITE_ROW) { // 獲得這行對應的資料,結果存放在statement中 // 獲得第0列的id int sid = sqlite3_column_int(stmt, 0); // 獲得第1列的name const unsigned char *sname = sqlite3_column_text(stmt, 1); // 獲得第2列的age int sage = sqlite3_column_int(stmt, 2); NSLog(@"%d %s %d", sid, sname, sage); } } else { NSLog(@"查詢語句非合法"); }}@end
使用工具類封裝模型
//// Student.h// 2_資料庫工具類封裝//// Created by xss on 14-11-2.// Copyright (c) 2014年 beyond. All rights reserved.//#import <Foundation/Foundation.h>@interface Student : NSObject// 學號@property (nonatomic, assign) int ID;// 姓名@property (nonatomic, copy) NSString *name;// 年齡@property (nonatomic, assign) int age;@end
工具類StudentDAO
//// StudentDAO.h// 2_資料庫工具類封裝//// Created by xss on 14-11-2.// Copyright (c) 2014年 beyond. All rights reserved.// 學生資料的CRUD(增刪改查)#import <Foundation/Foundation.h>@class Student;@interface StudentDAO : NSObject/** * 新增學生 * * @param student 需要添加的學生 */+ (BOOL)addStudent:(Student *)student;/** * 獲得所有的學生 * * @return 數組中裝著都是IWStudent模型 */+ (NSArray *)students;/** * 根據搜尋條件獲得對應的學生 * * @param condition 搜尋條件 */+ (NSArray *)studentsWithCondition:(NSString *)condition;@end
關鍵封裝的代碼
//// StudentDAO.m// 2_資料庫工具類封裝//// Created by xss on 14-11-2.// Copyright (c) 2014年 beyond. All rights reserved.//#import "StudentDAO.h"#import "Student.h"#import <sqlite3.h>@implementation StudentDAO// 重點~~~~加上static的作用:能保證_db這個變數只被StudentDAO.m內部訪問static sqlite3 *_db;// 重點~~~~工具類第一次載入的時候調用initialize方法+ (void)initialize{ // 0.獲得沙箱中的資料庫檔案名 NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"student.sqlite"]; // 1.建立(開啟)資料庫(如果資料庫檔案不存在,會自動建立) int result = sqlite3_open(filename.UTF8String, &_db); if (result == SQLITE_OK) { NSLog(@"成功開啟資料庫"); // 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(@"開啟資料庫失敗"); } for (int i = 0; i<30; i++) { NSString *name = [NSString stringWithFormat:@"beyond-%d", arc4random()%100]; int age = arc4random()%100; NSString *sql = [NSString stringWithFormat:@"insert into t_student (name, age) values('%@', %d);", name, age]; char *errorMesg = NULL; int result = sqlite3_exec(_db, sql.UTF8String, NULL, NULL, &errorMesg); if (result == SQLITE_OK) { NSLog(@"成功添加資料"); } else { NSLog(@"添加資料失敗:%s", errorMesg); } } }+ (BOOL)addStudent:(Student *)student{ // Sqlite3中所有的字串必須用單引號 NSString *sql = [NSString stringWithFormat:@"insert into t_student (name, age) values('%@', %d);", student.name, student.age]; char *errorMesg = NULL; // 兩個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) { // 真的查詢到一行資料 // 獲得這行對應的資料 Student *student = [[Student 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]; // 填補預留位置的內容,%在OC中是關鍵字,因此轉義 NSString *newCondition = [NSString stringWithFormat:@"%%%@%%", condition]; sqlite3_bind_text(stmt, 1, newCondition.UTF8String, -1, NULL); // 4.執行SQL語句,從結果集中取出資料 while (sqlite3_step(stmt) == SQLITE_ROW) { // 真的查詢到一行資料 // 獲得這行對應的資料 Student *student = [[Student 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;}@end
控制器中使用工具類為tableView提供資料來源,並且監聽搜尋方塊的模糊查詢
//// ViewController.m// 2_資料庫工具類封裝//// Created by xss on 14-11-2.// Copyright (c) 2014年 beyond. All rights reserved.//#import "ViewController.h"#import "Student.h"#import "StudentDAO.h"@interface ViewController ()<UISearchBarDelegate>// 從資料庫中返回的封裝好的對象數組,為tableView提供資料來源@property (nonatomic, strong) NSArray *students;@end@implementation ViewController#pragma mark - 懶載入- (NSArray *)students{ if (_students == nil) { _students = [StudentDAO students]; } return _students;}- (void)viewDidLoad{ [super viewDidLoad]; // 添加一個搜尋方塊,並設定代理 UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; searchBar.delegate = self; // headView self.tableView.tableHeaderView = searchBar;}#pragma mark - 搜尋方塊代理- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ // 直接覆蓋原來的對象數組 self.students = [StudentDAO studentsWithCondition:searchText]; // 重新整理表格 [self.tableView reloadData];}#pragma mark - tableView代理方法- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return self.students.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // 1.建立cell static NSString *ID = @"student"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; } // 2.設定cell的資料 Student *stu = self.students[indexPath.row]; cell.textLabel.text = stu.name; cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", stu.age]; return cell;}- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ [self.view endEditing:YES];}@end
ios中怎操作sqlite3資料庫操作
用 FMDB 這個開源庫 ! 對sqlite3做了封裝,用起來很方便 !
訪問SQlite資料庫的ios程式製作
現在如果使用SQLite話就用coreData。你那個功能就是做個分頁,跟資料庫的儲存沒有關係。別把資料Data儲存在資料庫中,這樣會使資料庫變的很大,並且讀取很不方便。把地址或者網址儲存下來,然後顯示出來就是了。