【发布时间】:2015-04-22 12:24:26
【问题描述】:
表值:
ID=1 CUSTOMERID=1 NAME=John EMAIL=email USERNAME=usernaeme
我正在使用此代码通过此代码从 Usertable 中获取 customerId
@try {
//CustomerIdField=@"admin";
// customerUsername=@"admin";
NSLog(@"the value of customerusername is %@",customerUsername);
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSLog(@"inside function");
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"EBook.db" ]];
const char *dbpath;
@try {
dbpath = [databasePath UTF8String];
NSLog(@"the const char is %s",dbpath);
}
@catch (NSException *exception) {
NSLog(@"the exception3 is %@",exception);
}
if (sqlite3_open(dbpath, &Ebookreaderdb) == SQLITE_OK)
{
NSString *selectSQL = [NSString stringWithFormat: @"SELECT CUSTOMERID FROM Usertable WHERE EMAIL=\"%@\"",customerUsername];
sqlite3_stmt *selstatement;
const char *select_stmt = [selectSQL UTF8String];
//NSMutableArray *resultArray = [[NSMutableArray alloc]init];
if (sqlite3_prepare_v2(Ebookreaderdb,
select_stmt, -1, &selstatement, NULL ) == SQLITE_OK)
{
NSLog(@"inside sqlite OK"); //this prints in log
if (sqlite3_step(selstatement) == SQLITE_ROW)
{
NSLog(@"inside sqlite ROW"); // this is also printing in log
NSString *userInfoStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selstatement,1)];
NSLog(@"val is %@",userInfoStr);
char *tmp = sqlite3_column_text(selstatement,1);
if (tmp == NULL)
CustomerIdField = nil;
else
CustomerIdField = [[NSString alloc] initWithUTF8String:tmp];
CustomerIdField = [[NSString alloc] initWithUTF8String:
(const char *) sqlite3_column_text(selstatement,1)];
NSLog(@"inside customer is %@",CustomerIdField);
// [resultArray addObject:name];
}
else{
NSLog(@"Not found");
// return nil;
}
sqlite3_reset(selstatement);
}
但我得到了这个异常Newpjtonfriday[2165:84017] the exception is 2 *** +[NSString stringWithUTF8String:]: NULL cString
我用谷歌搜索了上面的结果,到处都说该值为 null,这就是发生异常的原因。但在我的情况下,价值就在那里。
因为代码 NSLog(@"内部 sqlite ROW");
进入日志意味着表中存在一行。但无法获取它。
请帮忙
【问题讨论】:
-
顺便说一句,不要使用
stringWithFormat来构建SQL 语句。使用?占位符和sqlite3_bind_text函数(令人困惑的是,它使用从一开始的索引,与sqlite3_column_text的从零开始的索引不同)。 -
您调用了
sqlite3_reset(用于将绑定列重置为准备好的语句,因此可以再次执行该语句)并且您显然打算调用sqlite3_finalize(释放内存)。将reset替换为finalize。另外,您的意思是在此处打开数据库而不是关闭它吗?就个人而言,我会将数据库的打开与 SQL 语句的执行分开,但可以做任何你想做的事情,但只要确保每个打开都有其相应的关闭调用。不用说,这些烦人的小细节让像 FMDB 这样的库如此引人注目......