標籤:
SQLite採用動態資料類型,可以跨平台使用,不像CoreData是蘋果專用的:先介紹一下在Xcode中的簡單使用:
先串連資料庫
然後引入標頭檔#import <sqlite3.h>
代碼開始前先介紹一下sq語句:
//1.建立表
文法:
create table 表名(欄位1 類型 約束1 約束2, 欄位2 類型 約束1 約束2);
create table if not exists 表名(欄位1 類型 約束1 約束2, 欄位2 類型 約束1 約束2);
//案例:
需求:建立一個student表,表中的欄位有學號,姓名,年齡,學號約束條件:主鍵,自增,不可為空;姓名預設為‘無名氏’;年齡:大於16歲;
create table student(s_id integer primary key autoincrement not null, s_name text default ‘無名氏‘, s_age integer check (s_age > 16));
//2.插入資料
文法:
insert into 表名(欄位1, 欄位2, 欄位3)values(欄位1值, 欄位2值, 欄位3值);
//案例:插入學生姓名,年齡
insert into student(s_name, s_age)values(‘貝爺‘, 30);
insert into student(s_name, s_age)values(‘小李子‘, 40);
//3.更新資料
文法:
update 表名 set 欄位名1 = 修改值1, 欄位名2 = 修改值2 where 條件;
update student set s_age = 25 where s_age = 30;
//4.刪除資料
文法:
delete from 表名 where 條件;
//需求:刪除年齡為10歲的學生
delete from student where s_age = 10;
//5.查詢資料
文法:
select 要尋找的欄位 from 表名 where 條件;
select *from student where s_name = ‘貝爺‘;//查詢所有資訊
select s_id, s_age from student where s_name = ‘貝爺‘;
下面就開始代碼了:
#import "DataBaseHandle.h"
#import <sqlite3.h>
@interface DataBaseHandle ()
//資料庫的儲存路徑
@property (nonatomic, copy) NSString *dbPath;
@end
static DataBaseHandle *dataBase = nil;
@implementation DataBaseHandle
//單例
+ (DataBaseHandle *)shareDataBaseHandle {
if (dataBase == nil) {
dataBase = [[DataBaseHandle alloc] init];
}
return dataBase;
}
//懶載入需要給資料庫路徑賦值
- (NSString *)dbPath {
if (_dbPath == nil) {
//需求:路徑儲存在Documents檔案夾下,資料庫檔案為person.sqlite;
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
_dbPath = [documentPath stringByAppendingPathComponent:@"person.sqlite"];
}
return _dbPath;
}
//開啟資料庫;好多地方都會使用到資料庫,所以初始化一個資料庫 的靜態變數
static sqlite3 *db = nil;
- (void)openDataBase {
//開啟資料庫,使用int去接收開啟的結果
//第一個參數:表示資料庫的儲存路徑
//第二個參數:二級指標,資料庫的地址
int result = sqlite3_open([self.dbPath UTF8String], &db);
//result是個枚舉值,有很多種情況
if (result == SQLITE_OK) {
NSLog(@"資料庫開啟成功");
} else {
NSLog(@"資料庫開啟失敗");
}
}
- (void)updateWithUID:(NSInteger)uid {
NSString *updateStr = @"update person set name = ‘悟空‘ where uid = ?";
sqlite3_stmt *stmt = nil;
int result = sqlite3_prepare(db, updateStr.UTF8String, -1, &stmt, NULL);
if (result == SQLITE_OK) {
sqlite3_bind_int64(stmt, 1, uid);
if (sqlite3_step(stmt) == SQLITE_DONE) {
NSLog(@"更新資料成功");
} else {
NSLog(@"更新資料失敗");
}
} else {
NSLog(@"result = %d", result);
}
sqlite3_finalize(stmt);
}
- (void)deleteWithUID:(NSInteger)uid {
NSString *deleteStr = [NSString stringWithFormat:@"delete from person where uid = %ld", uid];
int result = sqlite3_exec(db, deleteStr.UTF8String, NULL, NULL, NULL);
if (result == SQLITE_OK) {
NSLog(@"刪除成功");
} else {
NSLog(@"刪除失敗");
}
}
以上只是簡單舉例。
注意點:OC中字串別忘了加@ 資料庫中的%@寫成‘%@’ 別忘了加單引號(字串加單引號,integer不用加)
[NSString stringWithFormat:@"delete from person where name = ‘%@’“, name1]與@"delete from person where name = ’name1”
區別在於若name1 = @“liubei”;語句1表示name屬性==liubei時滿足條件;語句2表示name的屬性==name1時滿足條件;
淺析SQLite資料庫(基礎教學)