【代碼筆記】iOS-FMDBDemo

来源:http://www.cnblogs.com/yang-guang-girl/archive/2017/07/27/7243234.html
-Advertisement-
Play Games

一,效果圖。 二,工程圖。 三,代碼。 ViewController.h ViewController.m ...


一,效果圖。

二,工程圖。

三,代碼。

ViewController.h

複製代碼
#import <UIKit/UIKit.h>
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"

@interface ViewController : UIViewController
{
    FMDatabase *db;
    NSString *database_path;
    
}
@end
複製代碼

 

ViewController.m

複製代碼
#import "ViewController.h"


#define DBNAME    @"personinfo.sqlite"
#define ID        @"id"
#define NAME      @"name"
#define AGE       @"age"
#define ADDRESS   @"address"
#define TABLENAME @"PERSONINFO"


@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    //初始化資料庫存放目錄
    [self addDocumentPath];
    //初始化界面
    [self addView];
    
    [super viewDidLoad];

}
#pragma -mark -functions
//初始化資料庫存放目錄
-(void)addDocumentPath
{
    //獲得Documents目錄
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSLog(@"--documents--%@",documents);
    //添加/號,使之變成一個完整的路徑
    database_path = [documents stringByAppendingPathComponent:DBNAME];
    NSLog(@"--database_path---%@",database_path);
    db = [FMDatabase databaseWithPath:database_path];
}
//初始化用戶界面
-(void)addView
{
 
    //新建資料庫
    UIButton *createBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    createBtn.frame=CGRectMake(60, 60, 200, 50);
    [createBtn addTarget:self action:@selector(doClickCreateButton) forControlEvents:UIControlEventTouchUpInside];
    [createBtn setTitle:@"createTable" forState:UIControlStateNormal];
    [self.view addSubview:createBtn];

    
    //插入資料庫
    UIButton *insterBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    insterBtn.frame=CGRectMake(60, 130, 200, 50);
    [insterBtn addTarget:self action:@selector(doClickInsertButton) forControlEvents:UIControlEventTouchUpInside];
    [insterBtn setTitle:@"insert" forState:UIControlStateNormal];
    [self.view addSubview:insterBtn];
    
    //更新資料庫
    UIButton *updateBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    updateBtn.frame=CGRectMake(60, 200, 200, 50);
    [updateBtn addTarget:self action:@selector(doClickUpdateButton) forControlEvents:UIControlEventTouchUpInside];
    [updateBtn setTitle:@"update" forState:UIControlStateNormal];
    [self.view addSubview:updateBtn];
    
    //刪除資料庫
    UIButton *deleteBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    deleteBtn.frame=CGRectMake(60, 270, 200, 50);
    [deleteBtn addTarget:self action:@selector(doClickDeleteButton) forControlEvents:UIControlEventTouchUpInside];
    [deleteBtn setTitle:@"delete" forState:UIControlStateNormal];
    [self.view addSubview:deleteBtn];
    
    //查看資料庫
    UIButton *selectBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    selectBtn.frame=CGRectMake(60, 340, 200, 50);
    [selectBtn addTarget:self action:@selector(doClickSelectButton) forControlEvents:UIControlEventTouchUpInside];
    [selectBtn setTitle:@"select" forState:UIControlStateNormal];
    [self.view addSubview:selectBtn];
    
    //多線程
    UIButton *multithreadBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    multithreadBtn.frame=CGRectMake(60, 410, 200, 50);
    [multithreadBtn addTarget:self action:@selector(doClickMultithreadButton) forControlEvents:UIControlEventTouchUpInside];
    [multithreadBtn setTitle:@"multithread" forState:UIControlStateNormal];
    [self.view addSubview:multithreadBtn];
    
    
}
#pragma -mark -doClickAction
//新建資料庫
- (void)doClickCreateButton{
    //sql 語句
    if ([db open]) {
        
        NSString *sqlCreateTable =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS];
        BOOL res = [db executeUpdate:sqlCreateTable];
        if (!res) {
            NSLog(@"error when creating db table");
        } else {
            NSLog(@"success to creating db table");
        }
        [db close];
        
    }
}

//插入資料庫
-(void)doClickInsertButton{
    if ([db open]) {
        NSString *insertSql1= [NSString stringWithFormat:
                               @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
                               TABLENAME, NAME, AGE, ADDRESS, @"張三", @"13", @"濟南"];
        BOOL res = [db executeUpdate:insertSql1];
        if (!res) {
            NSLog(@"error when insert db table");
        } else {
            NSLog(@"success to insert db table");
        }

        
        NSString *insertSql2 = [NSString stringWithFormat:
                                @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
                                TABLENAME, NAME, AGE, ADDRESS, @"李四", @"12", @"濟南"];
        BOOL res2 = [db executeUpdate:insertSql2];
        
        if (!res2) {
             NSLog(@"error when insert db table");
        }else{
             NSLog(@"success to insert db table");
        }
        [db close];
        
    }
    
}
//修改資料庫
-(void)doClickUpdateButton{
    if ([db open]) {
        NSString *updateSql = [NSString stringWithFormat:
                               @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'",
                               TABLENAME,   AGE,  @"15" ,AGE,  @"13"];
        BOOL res = [db executeUpdate:updateSql];
        if (!res) {
            NSLog(@"error when update db table");
        } else {
            NSLog(@"success to update db table");
        }
        [db close];
        
    }
    
}
//刪除資料庫
-(void)doClickDeleteButton{
    if ([db open]) {
        
        NSString *deleteSql = [NSString stringWithFormat:
                               @"delete from %@ where %@ = '%@'",
                               TABLENAME, NAME, @"張三"];
        BOOL res = [db executeUpdate:deleteSql];
        if (!res) {
            NSLog(@"error when delete db table");
        } else {
            NSLog(@"success to delete db table");
        }
        [db close];
        
    }
    
}
//查看資料庫
-(void)doClickSelectButton{
    
    if ([db open]) {
        NSString * sql = [NSString stringWithFormat:
                          @"SELECT * FROM %@",TABLENAME];
        FMResultSet * rs = [db executeQuery:sql];
        while ([rs next]) {
            int Id = [rs intForColumn:ID];
            NSString * name = [rs stringForColumn:NAME];
            NSString * age = [rs stringForColumn:AGE];
            NSString * address = [rs stringForColumn:ADDRESS];
            NSLog(@"id = %d, name = %@, age = %@  address = %@", Id, name, age, address);
        }
        [db close];
    }
}
//多線程操作資料庫
-(void)doClickMultithreadButton{
    
  
    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:database_path];
    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
    
    dispatch_async(q1, ^{
        for (int i = 0; i < 50; ++i) {
            [queue inDatabase:^(FMDatabase *db2) {
                NSString *insertSql1= [NSString stringWithFormat:
                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
                                       TABLENAME, NAME, AGE, ADDRESS];
                NSString * name = [NSString stringWithFormat:@"jack %d", i];
                NSString * age = [NSString stringWithFormat:@"%d", 10+i];
                
                
                BOOL res = [db2 executeUpdate:insertSql1, name, age,@"濟南"];
                if (!res) {
                    NSLog(@"error to inster data: %@", name);
                } else {
                    NSLog(@"succ to inster data: %@", name);
                }
            }];
        }
    });
    
    dispatch_async(q2, ^{
        for (int i = 0; i < 50; ++i) {
            [queue inDatabase:^(FMDatabase *db2) {
                NSString *insertSql2= [NSString stringWithFormat:
                                       @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
                                       TABLENAME, NAME, AGE, ADDRESS];
                
                NSString * name = [NSString stringWithFormat:@"lilei %d", i];
                NSString * age = [NSString stringWithFormat:@"%d", 10+i];
                
                BOOL res = [db2 executeUpdate:insertSql2, name, age,@"北京"];
                if (!res) {
                    NSLog(@"error to inster data: %@", name);
                } else {
                    NSLog(@"succ to inster data: %@", name);
                }
            }];
        }
    });
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
複製代碼
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 今天要給大家說的是兩個不同頁面之間的通信,通過一個拖拽demo來模擬; 首先,寫好基礎的拖拽代碼: 這是將div拖動變化的值存入到本地儲存localstorage,用JSON.stringify將其轉為字元串形式: 然後新建一個新建一個demo,獲取本地的數據: 通過onstorage這個方法實現兩 ...
  • HTML 超文本標記語言 html5 建立一個HTML文件:文件名 . 尾碼(html) 解析:就是去識別 註釋:就是給開發人員開的批註 瀏覽器不去解析(不去輸出) HTML的整體框架 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <tit ...
  • 數組去重+快速排序 //老數組var arr1 = [1,2,2,3,8,6,6,4,5,5];//定義新數組var arr2 = [ ];內部可運用布爾型進行判斷數組的唯一性 for(i=0;i<arr1.length;i++){ var status = 0;(true) for(j=0;j<a ...
  • 今早,上IT修真園裡,看到師兄大娃很負責任的將我任務里的項目的排版,3,6,7的列了出來。 謝謝師兄,那麼負責任的照看師弟。 言歸正傳,我一開始,直接按照師兄的指示,選擇性的優先修改底部。效果也達到了預期的效果。後來我為了查看我的項目跟psd圖的差別。就直接上我們的IT修真園的首頁,查看它的代碼了。 ...
  • 1. 如何創建嵌套的過濾器 //允許你減少集合中的匹配元素的過濾器, //只剩下那些與給定的選擇器匹配的部分。在這種情況下, //查詢刪除了任何沒(:not)有(:has) //包含class為“selected”(.selected)的子節點。 .filter(":not(:has(.select ...
  • Atwood’s Law是Jeff Atwood在2007年提出的:“any application that can be written in JavaScript, will eventually be written in JavaScript.”。據說,這隻是當時開的一個玩笑。不過,這個玩 ...
  • 使用Android DataBinding簡化Adapter的開發 ...
  • 它是如何觸發的? 這個值的狀態是燒錄在主板上,無法刷寫修改, 從0到1 不可逆,除非替換硬體 If a non-Knox boot loader or kernel has been installed on the device, Knox can no longer guarantee the ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...