我遇到SQLite的问题,我的应用程序在运行时崩溃,而我正在尝试建立与SQLite数据库的连接并获取其中的一些内容。这是我的代码:
-(IBAction)setInput:(id)sender
{
NSString *strStoreNumber;
NSString *strRegNumber;
strStoreNumber = StoreNumber.text;
strRegNumber = RegNumber.text;
lblStoreNumber.text = strStoreNumber;
lblRegNumber.text = strRegNumber;
NSString* databasePath = [[NSBundle mainBundle] pathForResource:@"tblStore" ofType:@"sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(@"Opened sqlite database at %@", databasePath);
//...stuff
}
else
{
NSLog(@"Failed to open database at %@ with error %s", databasePath, sqlite3_errmsg(database));
sqlite3_close (database);
}
NSString *querystring;
querystring = [NSString stringWithFormat:@"SELECT strStore FROM tblStore WHERE strStore = %@;", strStoreNumber];
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) // queryString = statement
{
szStore = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)];
szReg = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
} // while
}
sqlite3_finalize(statement);
// go on with putting data where you want
}
我在控制台中遇到的错误:
2012-05-07 09:39:33.619 CCoDBTry[962:f803] Opened sqlite database at /Users/*******/Library/Application Support/iPhone Simulator/5.1/Applications/5DB7A218-A0F6-485F-B366-91FD2F9BC062/CCoDBTry.app/tblStore.sqlite
2012-05-07 09:39:33.623 CCoDBTry[962:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSString stringWithUTF8String:]: NULL cString'
*** First throw call stack:
(0x1593022 0x1724cd6 0x153ba48 0x153b9b9 0x9d4973 0x27c9 0x1594e99 0xd714e 0xd70e6 0x17dade 0x17dfa7 0x17d266 0xfc3c0 0xfc5e6 0xe2dc4 0xd6634 0x147def5 0x1567195 0x14cbff2 0x14ca8da 0x14c9d84 0x14c9c9b 0x147c7d8 0x147c88a 0xd4626 0x1f82 0x1ef5)
terminate called throwing an exception(lldb)
非常感谢任何帮助!
编辑:请注意我在数据库中查找的值类型为VARCHAR
。我不确定是否知道这会有所作为。
答案 0 :(得分:1)
+[NSString stringWithUTF8String:]: NULL cString
抱怨您已将空值输入stringWithUTF8String:
。您的代码对此方法有两次调用,每次调用都会从查询结果中输入一个值。查看您的查询,您只选择一列strStore
。我会假设分配给szReg
的行失败,因为您正在尝试检索未在查询中选择的值。
答案 1 :(得分:1)
为了访问可能为null的值,我们不确定,我通常更喜欢事先检查它
char *sk = (char *)sqlite3_column_text(statement, 0);
if (sk != nil) {
szStore = [NSString stringWithUTF8String:sk];
}
这将阻止应用程序崩溃。