任何人都可以在我的iOS应用程序中帮助我查询SQLite查询吗?我想进行查询,这将取决于WHERE子句中的NSInteger varialbe,但我不知道如何将变量添加到查询中。
我试过这样的事情:
MySqlite *sqlConnect = [[MySqlite alloc] init];
sqlite3_stmt *statement = [sqlConnect makeSQL:"select * from table where id = %i", myIntegerVariable - 1];
但当然它不起作用。
感谢。
修改
MySqlite.h
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@interface MySqlite : NSObject {
}
- (sqlite3_stmt *)makeSQL:(char *)sql;
@end
MySqlite.m
#import "MySqlite.h"
@implementation MySqlite
NSString *dbFileName = @"data.sqlite";
- (void)createEditableCopyOfDatabaseIfNeeded {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *writableDBPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:dbFileName];
if ([fileManager fileExistsAtPath:writableDBPath]){
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbFileName];
if (! [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error] ) {
NSLog(@"Fail edit db");
}
}
- (sqlite3 *) getDBConnection{
[self createEditableCopyOfDatabaseIfNeeded];
sqlite3 *DBConnection;
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:dbFileName];
if( sqlite3_open([path UTF8String], &DBConnection) != SQLITE_OK) {
NSLog(@"Fail open db");
return FALSE;
}
return DBConnection;
}
- (sqlite3_stmt *)makeSQL:(char *)sql{
NSLog(@"Executing query: %s", sql);
sqlite3_stmt *statement = nil;
sqlite3 *db = [self getDBConnection];
if ( db ) {
if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL) != SQLITE_OK) {
NSLog(@"Error at query: %s", sqlite3_errmsg(db));
}
}
else {
NSLog(@"Error connect to db");
}
return statement;
}
@end
答案 0 :(得分:1)
如果我理解正确,您希望将一个整数变量注入SQL查询。如果是这样,下面的内容应该可以完成这项工作:
MySqlite *sqlConnect = [[MySqlite alloc] init];
sqlite3_stmt *statement = [sqlConnect makeSQL:[[NSString stringWithFormat:@"select * from table where id = %d", myIntegerVariable - 1] UTF8String]];
%d
是整数的修饰符。假设makeSQL选择器接受NSString SQL String