gpt4 book ai didi

iphone - SQLite 查询中的 NSInteger 变量

转载 作者:行者123 更新时间:2023-11-29 04:57:43 25 4
gpt4 key购买 nike

任何人都可以帮助我在 iOS 应用程序中进行 SQLite 查询吗?我想进行查询,这将取决于 WHERE 子句中的 NSInteger 变量,但我不知道如何将变量添加到查询中。

我试过这样的:

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

最佳答案

如果我理解正确的话,您想将一个整数变量注入(inject)到 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 字符串

关于iphone - SQLite 查询中的 NSInteger 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7612593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com