FMDatabase 的使用方法

CentOS 7下Oracle 11G RAC静默安装避坑指南:从网络规划到共享存储配置全流程 本文详细介绍了在CentOS 7环境下进行Oracle 11G RAC静默安装的全流程,包括网络规划、共享存储配置和系统参数调优等关键步骤。特别针对静默安装过程中的常见问题提供了实用的避坑指南和优化建议,帮助技术人员高效完成企业级数据库部署。 阅读详情

FMDatabase 的使用方法


- (NSString*) getPath {

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

   return [[pathsobjectAtIndex:0]stringByAppendingPathComponent:@"MyTable"] ;

}



1.创建数据库

-(void)CreateTable;

{

dataBase = [FMDatabasedatabaseWithPath:[selfgetPath]];

    if (![dataBase open])

       NSLog(@"OPEN FAIL");

    }

        

    [dataBaseexecuteUpdate:@"CREATE TABLE IF NOT EXISTS MyTable(aa float,bb text,cc integer,dd integer,ee text)"];

    [dataBaseclose];

}




2.查询数据

-(void)QueryData

{

//获取数据

   recordArray = [[NSMutableArrayalloc]init];

    

   db = [[FMDatabasealloc]initWithPath:[selfgetPath]];

    

    if ([db open]) {

       FMResultSet *rs = [dbexecuteQuery:@"SELECT * FROM MyTable"];

        while ([rs next]){

            OneRecord = [[OneRecord alloc]init];

            OneRecord.aa = [NSNumbernumberWithFloat:[rs doubleForColumn:@"aa"]];

            OneRecord.bb = [rs stringForColumn:@"bb"];

            OneRecord.cc = [NSNumbernumberWithInt:[rs intForColumn:@"cc"]];

            OneRecord.dd = [NSNumbernumberWithInt:[rs intForColumn:@"dd"]];

            OneRecord.ee = [rs stringForColumn:@"ee"];

            [recordArrayaddObject: OneRecord];

            [OneRecordrelease];

        }

        [rs close];

        [dbclose];

}


3.更新数据

-(void)UpdateData

{

if ([dbopen]) {

         [dbbeginTransaction];

         [dbexecuteUpdate:@"UPDATE MyTable SET aa = ? WHERE date = ?",aa1,aa2];

         [dbexecuteUpdate:@"UPDATE MyTable SET bb = ? WHERE date = ?",bb1,bb2];

         [dbexecuteUpdate:@"UPDATE MyTable SET cc = ? WHERE date = ?",cc1,cc2];

         [dbexecuteUpdate:@"UPDATE MyTable SET dd = ? WHERE date = ?",dd1,dd2];

         [dbcommit];

         db close];

   }


}


4。插入数据

-(void)insertData

{

//插入数据库

    [dbbeginTransaction];

    [dbexecuteUpdate:@"INSERT INTO MyTable (aa,bb,cc,dd,ee) VALUES (?,?,?,?,?)",

    NSNumber numberWithFloat:aa],bb,cc,dd,ee];

    db commit];

    db close];


}


5。官方的使用方法为:


Usage

There are three main classes in FMDB:

  1. FMDatabase - Represents a single SQLite database. Used for executing SQL statements.
  2. FMResultSet - Represents the results of executing a query on anFMDatabase.
  3. FMDatabaseQueue - If you're wanting to perform queries and updates on multiple threads, you'll want to use this class. It's described in the "Thread Safety" section below.

Database Creation

An FMDatabase is created with a path to a SQLite database file. This path can be one of these three:

  1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
  2. An empty string (@""). An empty database is created at a temporary location. This database is deleted with theFMDatabase connection is closed.
  3. NULL. An in-memory database is created. This database will be destroyed with theFMDatabase connection is closed.

(For more information on temporary and in-memory databases, read the sqlite documentation on the subject:http://www.sqlite.org/inmemorydb.html)

FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];

Opening

Before you can interact with the database, it must be opened. Opening fails if there are insufficient resources or permissions to open and/or create the database.

if (![db open]) {

    [db release];

    return;

}

Executing Updates

Any sort of SQL statement which is not a SELECT statement qualifies as an update. This includes CREATE, PRAGMA,UPDATE, INSERT, ALTER,COMMIT, BEGIN, DETACH,DELETE, DROP, END,EXPLAIN, VACUUM, and REPLACE statements (plus many more). Basically, if your SQL statement does not begin withSELECT, it is an update statement.

Executing updates returns a single value, a BOOL. A return value of YES means the update was successfully executed, and a return value of NO means that some error was encountered. If you use the -[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:] method to execute an update, you may supply anNSError ** that will be filled in if execution fails. Otherwise you may invoke the-lastErrorMessage and-lastErrorCode methods to retrieve more information.

Executing Queries

A SELECT statement is a query and is executed via one of the-executeQuery... methods.

Executing queries returns an FMResultSet object if successful, and nil upon failure. Like executing updates, there is a variant that accepts anNSError ** parameter. Otherwise you should use the-lastErrorMessage and-lastErrorCode methods to determine why a query failed.

In order to iterate through the results of your query, you use a while() loop. You also need to "step" from one record to the other. With FMDB, the easiest way to do that is like this:

FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];

while ([s next]) {

    //retrieve values for each record

}

You must always invoke -[FMResultSet next] before attempting to access the values returned in a query, even if you're only expecting one:

FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];

if ([s next]) {

    int totalCount = [s intForColumnIndex:0];

}

FMResultSet has many methods to retrieve data in an appropriate format:

  • intForColumn:
  • longForColumn:
  • longLongIntForColumn:
  • boolForColumn:
  • doubleForColumn:
  • stringForColumn:
  • dateForColumn:
  • dataForColumn:
  • dataNoCopyForColumn:
  • UTF8StringForColumnIndex:
  • objectForColumn:

Each of these methods also has a {type}ForColumnIndex: variant that is used to retrieve the data based on the position of the column in the results, as opposed to the column's name.

Typically, there's no need to -close an FMResultSet yourself, since that happens when either the result set is deallocated, or the parent database is closed.

Closing

When you have finished executing queries and updates on the database, you should -close the FMDatabase connection so that SQLite will relinquish any resources it has acquired during the course of its operation.

[db close];

Transactions

FMDatabase can begin and commit a transaction by invoking one of the appropriate methods or executing a begin/end transaction statement.

Data Sanitization

When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion. Instead, you should use the standard SQLite binding syntax:

INSERT INTO myTable VALUES (?, ?, ?)

The ? character is recognized by SQLite as a placeholder for a value to be inserted. The execution methods all accept a variable number of arguments (or a representation of those arguments, such as an NSArray,NSDictionary, or ava_list), which are properly escaped for you.

Alternatively, you may use named parameters syntax:

INSERT INTO myTable VALUES (:id, :name, :value)

The parameters must start with a colon. SQLite itself supports other characters, but internally the Dictionary keys are prefixed with a colon, donot include the colon in your dictionary keys.

NSDictionary *argsDict = [NSDictionary dictionaryWithObjectsAndKeys:@"My Name", @"name", nil];

[db executeUpdate:@"INSERT INTO myTable (name) VALUES (:name)" withParameterDictionary:argsDict];

Thus, you SHOULD NOT do this (or anything like this):

[db executeUpdate:[NSString stringWithFormat:@"INSERT INTO myTable VALUES (%@)", @"this has \" lots of ' bizarre \" quotes '"]];

Instead, you SHOULD do:

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", @"this has \" lots of ' bizarre \" quotes '"];

All arguments provided to the -executeUpdate: method (or any of the variants that accept a va_list as a parameter) must be objects. The following will not work (and will result in a crash):

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", 42];

The proper way to insert a number is to box it in an NSNumber object:

[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:42]];

Alternatively, you can use the -execute*WithFormat: variant to use NSString-style substitution:

[db executeUpdateWithFormat:@"INSERT INTO myTable VALUES (%d)", 42];

Internally, the -execute*WithFormat: methods are properly boxing things for you. The following percent modifiers are recognized:%@, %c, %s,%d, %D, %i,%u, %U, %hi,%hu, %qi, %qu,%f, %g, %ld,%lu, %lld, and %llu. Using a modifier other than those will have unpredictable results. If, for some reason, you need the% character to appear in your SQL statement, you should use%%.

Using FMDatabaseQueue and Thread Safety.

Using a single instance of FMDatabase from multiple threads at once is a bad idea. It has always been OK to make a FMDatabase objectper thread. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. Bad things will eventually happen and you'll eventually get something to crash, or maybe get an exception, or maybe meteorites will fall out of the sky and hit your Mac Pro. This would suck.

So don't instantiate a single FMDatabase object and use it across multiple threads.

Instead, use FMDatabaseQueue. It's your friend and it's here to help. Here's how to use it:

First, make your queue.

FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];

Then use it like so:

[queue inDatabase:^(FMDatabase *db) {

    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];

    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];

    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];


    FMResultSet *rs = [db executeQuery:@"select * from foo"];

    while ([rs next]) {

        …

    }

}];

An easy way to wrap things up in a transaction can be done like this:

[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {

    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];

    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];

    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];


    if (whoopsSomethingWrongHappened) {

        *rollback = YES;

        return;

    }

    // etc…

    [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];

}];

FMDatabaseQueue will make a serialized GCD queue in the background and execute the blocks you pass to the GCD queue. This means if you call your FMDatabaseQueue's methods from multiple threads at the same time GDC will execute them in the order they are received. This means queries and updates won't step on each other's toes, and every one is happy.


汽车BMS技术分享及其HIL测试方案 在全球碳中和目标的战略驱动下,新能源汽车产业正以指数级速度重塑交通出行格局。动力电池作为电动汽车的"心脏",其性能与安全性不仅直接决定了车辆的续航里程、使用寿命等关键指标,更深刻影响着消费者对电动汽车的市场接受度。而电池管理系统(Battery Management System, BMS)是动力电池安全运行与性能释放的核心技术支撑。 阅读详情

相关推荐

算法面试准备 - 手撕系列第五期 - 单头注意力机制(包括Self_atten和Cross_atten)

算法面试准备 - 手撕系列第五期 - 单头注意力机制(包括Self_atten和Cross_atten)

m0_62030579的博客 3608

FMDatabase的用法介绍

本人以后都会不定时的写一些关于IOS开发的教程,大家希望可提些意见,大家希望写些什么,对大家有帮助的,希望帮到大家: FMDatabase其实是一个很轻级的sqlite数据库封装库,用Object-C封装C,它主要有2个类:FMDatabase和FMResultSet 要使用它首先就要下载这个开源库,它的下载地址是:https://github.com/ccgus/fmdb 下载

Arlexovincy的专栏 1566

Wan 3.0提示词实战:从抄作业到改作业的完整技巧

AI视频生成中,提示词是决定成片质量的核心。视频模型依赖于文字约束来定义运动轨迹、镜头语言与物理合理性,提示词工程因此成为连接创意与技术的关键。本文从提示词的结构、资源获取、优化方法入手,结合Wan 3.0的模型特点,梳理了从官方模板到社区案例的实战路径,并强调运动一致性、风格词堆砌等常见问题。通过分解主体、动作、镜头等维度,帮助创作者快速找到适配的提示词,提升视频生成的稳定性与惊喜感。

weixin_29483277的博客 350

FMDB常用的数据类型以及sql语句

SQLite数据库的基本数据类型: 整数数据类型: (1)integer :整形数据,大小为4个字节 (2)bigint : 整形数据,大小为8个字节 (3)smallint:整形数据,大小为2个字节 (4)tinyint:从0到255的整形数据,存储大小为1字节 浮点数数据类型: (1)float:4字节浮点数 (2)double: 8字节浮点

ciwei_numberOne的博客 6692

绿标短网址app.10086.cn/xxxxx移动短网址缩短接口网址api调用php方式解析

绿标短网址app.10086.cn/xxxxx 移动网缩短接口网址api调用php方式解析 app.10086.cn是移动网站的接口,可以制作移动网等第三方官方网站域名的任意生成接口,由于是认证企业,可以再抖音 微信 qq等第三方渠道正常打开不拦截提示,第三方网址,头条文章等,效果非常号,这里记录下api接口,纯技术php生成,具体规则可以去抖音的开放平台去申请对应接口 。这里用我php模拟抓包获取方式 GET http://www.app10086cn.cn/?i=app.10068.cnHTTP/1.1

qq_20300095的博客 5907

在统信UOS Server 20上踩坑记:手把手教你搞定openGauss 5.0.0企业版安装(附常见报错解决方案)

本文详细记录了在统信UOS Server 20上安装openGauss 5.0企业版的实战经验,包括环境准备、依赖库问题、目录权限、内存参数调优等常见问题的解决方案。通过伪装系统标识、建立软链接、调整内存参数等方法,成功克服国产操作系统与企业级数据库的兼容性挑战,为开发者提供了一份深度排雷指南。

weixin_28698059的博客 263

【ios开发】使用FMDB封装类的sqlite数据库操作

今天第一次学习FMDB,实现了增删查改,列几个例子供大家参考创建,插入,更新和删除:使用executeUpdate方法,而查询则用executeQuery 1.实例化FMDatabase//paths: ios下Document路径,Document为ios中可读写的文件夹NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDo...

diezhi9415的博客 211

从零玩转GD32单片机CAN总线:手把手实战配置与源码解析

本文提供了一份基于GD32单片机的CAN总线实战入门指南。从硬件连接(GD32F103C8T6与TJA1050收发器)到软件配置,详细解析了CAN初始化、波特率计算、过滤器设置及中断收发等核心源码。通过手把手的回环测试示例与常见问题排查,帮助开发者快速掌握CAN总线通信的关键配置与调试技巧。

g5h6i7j的博客 481

数据库操作(使用FMDB)

iOS中原生的SQLite API在使用上相当不友好,在使用时,非常不便。于是,就出现了一系列将SQLite API进行封装的库,例如FMDB、PlausibleDatabase、sqlitepersistentobjects等,FMDB (https://github.com/ccgus/fmdb) 是一款简洁、易用的封装库,这一篇文章简单介绍下FMDB的使用。 在FMDB下载文件

Fly的技术博客 1277

MCGS触摸屏Modbus TCP通讯实战:从寄存器写入到字符串处理的完整代码解析

本文详细解析了MCGS触摸屏通过Modbus TCP协议实现寄存器写入和字符串处理的完整代码,涵盖单寄存器写入、多寄存器写入及字符串传输等核心技术。文章还提供了MCGS组态环境中的实战配置步骤和常见问题排查方法,帮助开发者快速掌握工业自动化通讯的关键技术。

study的专栏 755

基于ESP32-S3与模块化设计的立创桌面充电站:从硬件架构到Web控制实战

本文详细介绍了基于ESP32-S3与模块化设计的立创桌面充电站项目,涵盖从硬件架构到Web控制的全流程实战。项目采用模块化设计,支持自由组合快充模块,并通过ESP32-S3实现智能监控,用户可通过本地网页实时查看各接口电压、电流与功率数据。文章重点解析了基板、连接板与充电模块三大核心部件的设计,特别是大电流PCB的“开窗贴铜”处理技巧,并提供了固件刷写与Web控制面板的配置指南。

weixin_36122351的博客 293

【汇总】解决IndexedDB报Failed to execute ‘transaction‘ on ‘IDBDatabase‘

【汇总】解决IndexedDB报Failed to execute 'transaction' on 'IDBDatabase'

码农的艺术 4187

VMware系列:此平台不支持虚拟化 Intel-VT-x/EPT 或 AMD-V/RVI

VMware系列:此平台不支持虚拟化 Intel-VT-x/EPT 或 AMD-V/RVI

weixin_54626591的博客 1万+

FMDataBase总结

iOS开发中FMDataBase使用方法总结,有需要的朋友可以参考下。 一.SQLite数据库 SQLite数据库是一种嵌入式的轻量关系型文件数据库,该数据库的所有内容存在一个文件中,一个数据库就是一个文件。该数据库占用资源很少,主要用于各种移动设备上. SQLite数据库的基本数据类型: 整数数据类型: (1)integer :整形数据,大小为4个字

yuj9006的专栏 1027

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

iOS FMDatabase 本地数据库的创建和几个基本使用方法

使用数据库之前当然要先在网上下载FMDB的库,然后添加到自己的工程里面去。没有的请点击下面的来下载 fmdb 在FrameWork里添加“libsqulite3.0.dylib”,不然库托进去后会引起大量报错。 一般来说,我们把一个应用的数据库建在当前程序的沙盒里,所以,我们要先取得沙盒的路径 在AppDelegate.m中 1 2 3 4 5 6

JoJo-追求卓越~ 3351

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

FMDatabase 的使用(转)

FMDatabase 对SQLite 的API进行了很好的封装,使用起来很方便。 使用说明:https://github.com/ccgus/fmdb (1)引入相关文件。 FMDatabase.h FMDatabase.m FMDatabaseAdditions.h FMDatabaseAdditions.m FMDatabasePool.h FMDatabasePool.m ...

weixin_30907935的博客 137

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

FMDatabase介绍使用

本人以后都会不定时的写一些关于IOS开发的教程,大家希望可提些意见,大家希望写些什么,对大家有帮助的,希望帮到大家: FMDatabase其实是一个很轻级的sqlite数据库封装库,用Object-C封装C,它主要有2个类:FMDatabase和FMResultSet 要使用它首先就要下载这个开源库,它的下载地址是:https://github.com/ccgus/fmdb 下载

江湖两把刀的技术博客 3773
上一篇: IOS 下使用AdMob广告
下一篇: App Icons on iPad and iPhone
ch_soft
博客等级 码龄17年 828粉丝 166原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值