FMDB操作 SQLite的查询操作方法
FMDB的查询方法简单操作
- (FMResultSet*)executeQuery:(NSString*)sql, ...;
- (FMResultSet*)executeQueryWithFormat:(NSString*)format, ...;
- (FMResultSet*)executeQuery:(NSString*)sql withArgumentsInArray:(NSArray*)arguments;
- (FMResultSet*)executeQuery:(NSString*)sql withParameterDictionary:(NSDictionary*)arguments;
写在前面:网上的资料
1.创建一个数据库,并创建表testTable
@"create table if not exists testTable('id' integer primary key autoincrement,'name' text, 'age' integer, 'birth' text)"
在里面插入数据,如图所示

下面来进行测试
- (FMResultSet *)executeQuery:(NSString*)sql, ...;
[_db executeQuery:@"select name,age from testTable"];

现在换一种查询方式
[_db executeQuery:@"select ?,? from testTable;",@"name",@"age"];

并没有查询到我们想要的数据,我们在where语句中试一下
[_db executeQuery:@"select name,age from testTable where name = ?;", @"zhangsan"];
这里我门找到了name = zhangsan的数据

接下来我们查询age,
[_db executeQuery:@"select name,age from testTable where age = ?;", @(18)];

也查到我们想要的数据。上面的查询语句中,我们传入的age是NSNumber类型的,我们试一下能否是String类型
[_db executeQuery:@"select name,age from testTable where age = ?;", @"18"];
这里也是能够查询到的,截图和上面一样,就不再重复上传了
我们再来尝试满足两个条件人意一个条件的情况,看看结果
[_db executeQuery:@"select name,age from testTable where age = ? or name = ?;", @(18), @"zhangsan"];

总结一下,?只能够用来对数据进行占位,不能对列名称进行占位
PS;[_db executeQuery:@"select name,age from testTable where ? = ?;", @"name",@"zhangsan"];
出现了意想不到的效果。
- (FMResultSet*)executeQueryWithFormat:(NSString*)format, ...;
[_db executeQueryWithFormat:@"select %@,%@ from testTable",@"name", @"age"];

仍然没有找多我们想要的数据,着复合我们的预期
[_db executeQueryWithFormat:@"select name,age from testTable where name = %@;", @"zhangsan"]

结果如上。PS,由于结果相同,我没有重新截图,直接使用刚才的截图
[_db executeQueryWithFormat:@"select name,age from testTable where age = %@;", @"18"];
这里age = %@, 年龄也是@”“类型,能够查询到数据

接下来尝试数据类型不对应的情况
age = %@;", @(18) 和上面的结果相同
age = %d;", 18 和上面结果相同
age = %d;", @"18"
会出现查询失败,并且控制台为可输入状态,真机不清楚
age = %@;", 18
这个会直接崩溃。不能这样写
- (FMResultSet*)executeQuery:(NSString*)sql withArgumentsInArray:(NSArray*)arguments;
[_db executeQuery:@"select name, age from testTable where name = ? or age = ?" withArgumentsInArray:@[@"zhangsan", @(18)]];
全部使用?,并且后面使用OC对象

[_db executeQuery:@"select name, age from testTable where name = %@ or age = %@" withArgumentsInArray:@[@"zhangsan", @(18)]]
使用frrmat方式,会报错,信息如下

- (FMResultSet*)executeQuery:(NSString*)sql withParameterDictionary:(NSDictionary*)arguments;
使用字典.个人进行尝试
[_db executeQuery:@"select name, age from testTable where name = :name or age = :age;" withParameterDictionary:@{@"name":@"zhangsan",@"age":@(18)}];
成功得到结果。

上看的例子,: name 和ket name是对应的,可以用其他的代替,例如
[_db executeQuery:@"select name, age from testTable where name = :value1 or age = :value2;" withParameterDictionary:@{@"value1":@"zhangsan",@"value2":@(18)}]
这样也是能够得到上面的结果。
总结。查询语句中,为了代码的可读性,我们可能会使用占位符。FDMB中,占位符只能对我门需要传入的值进行占位,不能对选项进行占位,例如
select name , age from table where nane = ‘hahaha’ or age = ’18’
我门只能对hahaha和18,这两个需要传入的值进行占位,name,age ,table 都是不能够的进行占位的