我试图在运行时通过 Objective-C 创建一个 SQLite3 数据库文件。我正在尝试创建一个名为“tblStore”的表。我希望将字段名称称为“strStoreNumber”和“strStoreReg”。我是 iOS 和 SQLite 的新手,所以我很难找到执行此操作的语法。除了创建表之外,我希望创建的表不驻留在应用程序包中,而是驻留在/存储在手机上的某个位置。该表需要是可读/可写的。我已经阅读了“用户沙箱”和“文档目录”。我不确定我是否理解两者之间的区别。理想情况下,我的应用程序将使用一个按钮从文本字段中获取输入。将文本字段的输入放入字符串后,
回顾一下: 1. Obj-C/SQLite 创建一个名为“tblStore”的表,其中包含“strStoreNumber”和“strStoreReg”字段的语法是什么?2.db文件应该放在哪里?我需要读取和写入 tblStore db 文件。3. “用户沙箱”和“文档目录”有什么区别?
这是我目前拥有的:
-(IBAction)setInput:(id)sender
{
NSString *strStoreNumber;
NSString *strRegNumber;
NSString *tableName = @"tblStore";
NSString *dbStrStore = @"strStore";
NSString *dbStrReg = @"strReg";
strStoreNumber = StoreNumber.text;
strRegNumber = RegNumber.text;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths lastObject];
NSString* databasePath = [documentsDirectory stringByAppendingPathComponent:@"tblStore.sqlite"];
// NSString* databasePath = [[NSBundle mainBundle] pathForResource:@"tblStore" ofType:@"sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(@"Opened sqlite database at %@", databasePath);
char *err;
NSString *sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' TEXT PRIMARY KEY, '%@' TEXT);", tableName, dbStrStore, dbStrReg];
if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK)
{
sqlite3_close(database);
NSAssert(0, @"Table failed to create.");
}
//...stuff
}
else
{
NSLog(@"Failed to open database at %@ with error %s", databasePath, sqlite3_errmsg(database));
sqlite3_close (database);
}
NSString *querystring;
// create your statement
querystring = [NSString stringWithFormat:@"SELECT strStore, strReg FROM tblStore WHERE strStore = %@ AND strReg = %@;", strStoreNumber, strRegNumber];
const char *sql = [querystring UTF8String];
NSString *szStore = nil;
NSString *szReg = nil;
sqlite3_stmt *statement = nil;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL)!=SQLITE_OK) //queryString = Statement
{
NSLog(@"sql problem occured with: %s", sql);
NSLog(@"%s", sqlite3_errmsg(database));
}
else
{
// you could handle multiple rows here
while (sqlite3_step(statement) == SQLITE_ROW)
{
szStore = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];
szReg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
}
}
sqlite3_finalize(statement);
lblStoreNumber.text = szStore;
lblRegNumber.text = szReg;
}
当我运行我的应用程序时,我收到以下错误:
2012-05-10 14:58:38.169 CCoDBTry[355:f803] Opened sqlite database at /Users/Matt****/Library/Application Support/iPhone Simulator/5.1/Applications/5DB7A218-A0F6- 485F-B366-91FD2F9BC062/Documents/tblStore.sqlite
2012-05-10 14:58:38.307 CCoDBTry[355:f803] sql problem occured with: SELECT strStore, strReg FROM tblStore WHERE strStore = 8053 AND strReg = 4;
2012-05-10 14:58:38.308 CCoDBTry[355:f803] no such column: strStore
我感谢任何抽出时间来解释其中一些内容的人,因为我很新,并且在完成我尝试过的一些事情方面没有成功。非常感谢你的帮忙!