IOS sqlite 基础
来源:互联网 发布:知乎 怎么搜文章 编辑:程序博客网 时间:2024/05/23 12:25
1,导入libsqlite3.0.dylib库
文件中:#import"sqlite3.h"
2,创建数据库
#define kDocDir [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
#define dbPath [kDocDir stringByAppendingPathComponent:@"test.db"]
sqlite3 *db;
if (sqlite3_open([dbPath UTF8String], &db) !=SQLITE_OK) {
sqlite3_close(db);
NSAssert(0,@"数据库打开失败。");
return;
}
3,创建表table1, 三个不同类型的字段id是整形,name是字符串,image是二进制
char *sqlStr ="CREATE TABLE table1 (id integer, name text, image blob)";
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, sqlStr, -1, &statement,nil) !=SQLITE_OK) {
NSLog(@"Error: failed to prepare statement:create table1");
return;
}
int success = sqlite3_step(statement);
sqlite3_finalize(statement);
if ( success != SQLITE_DONE) {
NSLog(@"Error: failed to dehydrate:CREATE TABLEtable1");
return;
}
4,插入数据,注意问号的个数要和参数匹配
int idvalue;
NSString *namevalue";
NSData *image;
sqlStr = "INSERT INTO table1 VALUES(?,?,?)";
int success = sqlite3_prepare_v2(db, sqlStr, -1, &statement,NULL);
if (success != SQLITE_OK) {
NSLog(@"Error: failed to insert into table1");
}
sqlite3_bind_int(statement, 1, [idvalue integerValue]);//第二个参数从1开始,与后面查询数据的时候有区别
sqlite3_bind_text(statement, 2, [namevalue UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 3, [image bytes], (int)[image length],SQLITE_TRANSIENT);
success = sqlite3_step(statement);
sqlite3_finalize(statement);
if (success == SQLITE_ERROR) {
NSLog(@"Error: failed to insert into the database with message.");
return;
}
5, 查询数据
sqlStr = "SELECT * FROM table1";
if (sqlite3_prepare_v2(db, sqlStr, -1, &statement,NULL) !=SQLITE_OK) {
NSLog(@"Error: failed to prepare statement with message:gettable1.");
return;
}
//查询结果集中一条一条的遍历所有的记录,这里的数字对应的是列值。
while (sqlite3_step(statement) ==SQLITE_ROW) {
int tempint=sqlite3_column_int(statement, 0);//这里要从0开始,注意与插入的时候序号的区别
char *temp=(char *)sqlite3_column_text(statement, 1);
NSString *tempstr=temp?[NSString stringWithUTF8String:temp]:@"";
int length=sqlite3_column_bytes(statement,2);//获取到二进制的数据的长度
Byte* bytes=(Byte*)sqlite3_column_blob(statement,2);
NSData *data=[NSData dataWithBytes:byteslength:length];
}
6,关闭数据库
sqlite3_close(db);
- IOS sqlite 基础
- iOS SQLite基础内容简介
- iOS 数据存储 - 03SQLite基础
- SQLite基础
- Sqlite 基础
- SQlite基础
- sqlite 基础
- Sqlite基础
- SQLite 基础
- SQLite基础
- sqlite 在 ios 开发的使用(基础)
- iOS开发基础技能之数据库(SQLite)
- IOS -- Sqlite
- ios sqlite
- iOS sqlite
- iOS SQLite
- iOS sqlite
- iOS sqlite
- 、做最好的自己--【我的2014】
- Android资源图片内存占用及优化
- Face The Right Way POJ 3276
- Linux添加硬盘 分区 格式化 挂载
- wireahsrk 解析 arp包 实例
- IOS sqlite 基础
- Fraction to Recurring Decimal|leetcode题解
- ffmpeg neon优化必看!!android下编译ffmpeg with neon的正确方法(已验证)
- 第5章 循环和关系表达式
- android官网打不开,这有代理站哦~
- CSS 基础知识(一)
- [创业]Peter Thiel《Zero to One》中的13条逆向创业观点
- memcached初学
- 第6章 分支语句、逻辑操作符、基本文件IO