使用SQLite数据库存储数据(1)操作SQLite数据库

在使用SQLite API函数如有疑问,可以参考官方函数文档:

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, &noteDB) == 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传的是地址,因为该函数要通过地址引用来写报错字符信息。

原文地址:https://www.cnblogs.com/tuncaysanli/p/2727947.html