使用SQLite数据库存储数据(1)-操作SQLite数据库
2012-10-17 16:35
543 查看
在使用SQLite API函数如有疑问,可以参考官方函数文档:
http://www.sqlite.org/c3ref/funclist.html
操作SQLite数据库
SQLite数据库是文件数据库,是保存在文件系统中的。因此需要知道文件保存到哪里,下面的代码中,我们将Notebook.sqlite数据库存放在Documents目录下。其中涉及到SQLite数据库的创建、打开、创建数据表和关闭数据库等等操作。
SQLite的策略是如果有该数据库文件就打开,如果没有就创建文件,也就是创建数据库。这里要注意,使用的是C语法,sqlite3_open传入的是数据库的地址。
下面的代码负责将NSString 对象转换为const char * 的C类型数据。
const char *dbpath = [databasePath UTF8String];
在调用sqlite3_exec(noteDB, sql_str, NULL, NULL, &errMsg)函数时,errMsg传的是地址,因为该函数要通过地址引用来写报错字符信息。
http://www.sqlite.org/c3ref/funclist.html
操作SQLite数据库
SQLite数据库是文件数据库,是保存在文件系统中的。因此需要知道文件保存到哪里,下面的代码中,我们将Notebook.sqlite数据库存放在Documents目录下。其中涉及到SQLite数据库的创建、打开、创建数据表和关闭数据库等等操作。
NSString *docsDir; NSArray *dirPaths;
// 获取 documents 目录 dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); docsDir = [dirPaths objectAtIndex:0];
// 构造数据库文件路径 databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"Notebook.sqlite"]]; NSFileManager *fileMgr = [NSFileManager defaultManager]; if([fileMgr fileExistsAtPath:databasePath] == NO){ const char *dbpath = [databasePath UTF8String]; // 创建数据库,并打开数据库 // SQLite的策略是如果有该文件就打开,如果没有就创建文件,也就是创建数据库。 if (sqlite3_open(dbpath, ¬eDB) == SQLITE_OK) { char *errMsg; const char *sql_str ="CREATE TABLE IF NOT EXISTS Notebook (ID INTEGER PRIMARY KEY AUTOINCREMENT, Whattime Text, Address TEXT, What TEXT, Who TEXT, NOTE TEXT)"; // 创建数据表 Notebook if(sqlite3_exec(noteDB, sql_str, NULL, NULL, &errMsg) != SQLITE_OK){ NSLog(@"Failed to create table"); }
// 关闭数据库 sqlite3_close(noteDB); } else { NSLog(@"Failed to open/create database"); } }
SQLite的策略是如果有该数据库文件就打开,如果没有就创建文件,也就是创建数据库。这里要注意,使用的是C语法,sqlite3_open传入的是数据库的地址。
下面的代码负责将NSString 对象转换为const char * 的C类型数据。
const char *dbpath = [databasePath UTF8String];
在调用sqlite3_exec(noteDB, sql_str, NULL, NULL, &errMsg)函数时,errMsg传的是地址,因为该函数要通过地址引用来写报错字符信息。
相关文章推荐
- 【数据存储】SQLite数据库存储(2)----- 使用SQLite数据库并完成更新操作
- 无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)
- 使用嵌入式关系型SQLite数据库存储数据之使用SQLiteDatabase操作SQLite数据库
- 使用SQLiteDatabase操作SQLite数据库存储数据
- android(18)_数据存储与访问_SQLite数据库_使用SQLiteDatabase操作SQLite数据库及事务
- Andorid:使用嵌入式关系型SQLite数据库存储数据之CRUD:
- scrapyl使用pymysql操作数据库存储数据(存入多个表)
- Android用SQLite数据库对数据存储及操作的总结
- 使用嵌入式关系型SQLite数据库存储数据
- 使用Hive或Impala执行SQL语句,对存储在Elasticsearch中的数据操作
- Unity3d在安卓平台下使用sqlite存储操作数据
- 使用嵌入式关系型SQLite数据库存储数据
- Android进阶#(5/12)独特高效的数据存储——SQLite数据库_数据库框架ActiveAndroid的使用与基本原理
- 如何在 ASM 存储中使用 Data Pump (expdp impdp)进行数据导出导入操作
- 使用stringRedisTemplate操作redis hash结构数据只能存储String类型的问题
- 使用嵌入式关系型SQLite数据库存储数据
- Android数据存储—使用SQLite数据库
- 【数据存储】SQLite数据库存储(9)----- 操作联系人的ContentProvider
- 使用嵌入式关系型SQLite数据库存储数据
- Android数据存储之Sqlite数据库的俩种使用方式