您的位置:首页 > 其它

FMDB的简单使用方法

2014-09-21 14:10 218 查看
FMDB下载地址:(https://github.com/ccgus/fmdb)
sqlite:(http://www.sqlite.org/docs.html)
FMDatabase *db = [FMDatabase databaseWithPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/mySqlite.sqlite"]];
[db open];//打开之后,若之前不存在这个数据库,此时便会在Documents文件夹下生成这个数据库,对数据库进行操作首先要打开数据库
/*官方文档
Executing Updates
Any sort of SQL statement which is not a SELECT statement qualifies as an update. This includes CREATE, 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 with SELECT, it is an update statement.
任何类型的SQL语句除了select语句,包括使用create,update,insert,alter,commit,delete等等*/
[db executeUpdate:@"create table Person (name text)"];//创建了一个表     
[db executeUpdate:@"insert into Person (name) values(?)", @"zhangsan" ];//向Person表的name列下增加了一个zhangsan
[db executeUpdate:@"update Person set name = ? where name = ?", @"lisi", @"zhangsan"];//将名字是zhangsan的修改为lisi
[db executeUpdate:@"delete from Person where name = ?", @"lisi"];//删除lisi







/*官方文档
Executing queries returns an FMResultSet object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the -lastErrorMessage and -lastErrorCode methods to determine why a query failed.//使用  -lastErrorMessage可查看错误信息

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:
//为了迭代访问查询结果,使用while()循环,
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 next]在获取返回值之前,即使仅仅获取一个值
FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"];
if ([s next]) {
int totalCount = [s intForColumnIndex:0];
}*/
FMResultSet * s = [db executeQuery:@"select * from Person"];
while ([s next]) {
NSString * name = [s stringForColumn:@"name"];//根据列名返回这一列的所有值
NSLog(@"name == %@",name);
NSString * name1 = [s stringForColumnIndex:1];//根据列的下标返回这一列的所有值
NSLog(@"name1 == %@", name1);
}
[db close];//结束操作后要关闭数据库
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: