標籤:
程式運行結果如下 :
輸入name和age,點擊"確認插入"按鈕,即插入一條記錄到資料庫.
程式碼如下:(有詳細注釋,相信大家都看得懂哈!!!)
//
// ViewController.m
// 02 SQLite的基本操作
//
// Created by mac1 on 15/10/6.
// Copyright (c) 2015年 www.iphonetrain.com. All rights reserved.
//
#import "ViewController.h"
//匯入庫檔案
#import <sqlite3.h>
@interface ViewController ()
//姓名
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
//年齡
@property (weak, nonatomic) IBOutlet UITextField *ageTextField;
@property (nonatomic,assign)sqlite3 *db; //全域變數預設為NULL
//"確認插入"按鈕
- (IBAction)insertAction;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//構建資料庫的路徑
NSString *dbFilePath = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents/test.db"];
//列印資料庫儲存路徑
NSLog(@"dbFilePath = %@",dbFilePath);
//1.建立資料庫,如果沒有資料庫,則會建立
_db = NULL;
int status = sqlite3_open(dbFilePath.UTF8String, &_db);
if (status == SQLITE_OK) {
NSLog(@"開啟資料庫成功!");
//2.建立表
char *errmsg = NULL;
sqlite3_exec(_db, "CREATE TABLE IF NOT EXISTS t_user (id integer PRIMARY KEY ,name text, age integer)", NULL, NULL, &errmsg);
if (errmsg) {
NSLog(@"建立表失敗!");
}
}
//查詢資料
[self queryData];
}
//"確認插入"按鈕被點擊
- (IBAction)insertAction {
//DML 插入
NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO t_user (name,age) VALUES (‘%@‘,‘%ld‘)",_nameTextField.text,[_ageTextField.text integerValue]];
//插入資料
char *error = NULL;
sqlite3_exec(_db, insertSql.UTF8String, NULL, NULL, &error);
if (error) {
NSLog(@"插入記錄失敗!");
}
}
//DQL 查詢語句的使用
- (void)queryData{
//準備查詢(檢查sql語句的合法性)
//參數值-1 表示程式內部計算大小
sqlite3_stmt *stmt = NULL;
int status = sqlite3_prepare_v2(_db, "SELECT * FROM t_user", -1, &stmt, NULL);
//表示有資料
if (status == SQLITE_OK) {
//sqlite3_step(stmt) == SQLITE_ROW 當前stmt指向的資料有值
while (sqlite3_step(stmt) == SQLITE_ROW) {
//取出一條資料中的name欄位中的值
const unsigned char *name = sqlite3_column_text(stmt, 1);
//取出一條資料中的age欄位中的值
int age = sqlite3_column_int(stmt, 2);
NSLog(@"name = %s , age = %d",name,age);
}
}
}
@end
不過,對資料庫的操作,一般使用第三方架構 FMDB 操作
:https://github.com/ccgus/fmdb
SQLite 的簡單使用