【发布时间】:2015-01-04 00:01:09
【问题描述】:
我使用 sqlite manager(mozilla) 创建了数据库并在其中创建了表。现在我想将该数据检索到我的 iOS 应用程序中。我该如何以编程方式进行处理。你能请任何人帮助我如何做到这一点。谢谢。
【问题讨论】:
我使用 sqlite manager(mozilla) 创建了数据库并在其中创建了表。现在我想将该数据检索到我的 iOS 应用程序中。我该如何以编程方式进行处理。你能请任何人帮助我如何做到这一点。谢谢。
【问题讨论】:
把那个“sqlite”文件放到App的包里,然后你就可以使用那个文件了。
【讨论】:
使用这样的东西:
导入:
#import "sqlite3.h"
检查数据库是否存在:
NSString *docsDir;
NSArray *dirPaths;
NSString *databasePath;
sqlite3 *DB;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"YourDbName.sqlite"]]; //put your db name here
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &DB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS YourTable (Value INTEGER PRIMARY KEY, column TEXT)";
if (sqlite3_exec(DB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
}
sqlite3_close(DB);
}
}
获取数据库值:
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &DB) == SQLITE_OK) //News is a sqlite variable initialized like this: sqlite3* News;
{
NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM YourDBName"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(DB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString* example; //example variable to assign data from db
example = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]; //change the 0 to 1,2,3.... for every column of your db
}
sqlite3_finalize(statement);
}
sqlite3_close(DB);
}
【讨论】:
要将该数据检索到您的 iOS 应用程序中。请按照以下步骤操作 让我们考虑您的 SQlite DB 有名称 YourDB ,其中包含表信息和列 Name、Place 和 City 和 DatabasePath 是您存储 SQlite DB 的路径
const char *dbpath = [DatabasePath UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &YourDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
@"SELECT Place, City FROM students WHERE Name=Bob"];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(YourDB,query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *Place = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(
statement, 0)];
NSString *City = [[NSString alloc]
initWithUTF8String:(const char *)
sqlite3_column_text(statement, 1)];
}
sqlite3_finalize(statement);
}
sqlite3_close(YourDB);
}
【讨论】: