gpt4 book ai didi

objective-c - SQLite insert语句不会在表中放置记录

转载 作者:行者123 更新时间:2023-12-03 16:31:59 25 4
gpt4 key购买 nike

此函数中的所有内容似乎都按预期工作,只是数据库表中实际上没有显示任何记录。如果我直接通过Firefox sqlite管理器插件输入sql,则记录会很好。可能有些令人沮丧的愚蠢,有什么想法吗?

- (IBAction)buttonInsertRecord:(id)sender
{
// initializing db file access
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"KJV.sqlite"];

// testing to see if database was found
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
// database not found
labelStatus.text = @"database not found";
}
else
{
// database not found
labelStatus.text = @"database found";
}

sqlite3_stmt *statement;
sqlite3 *dbPointer;

if (sqlite3_open(dbPath.UTF8String, &dbPointer) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO users (user_name, user_id) VALUES ('testuser', null);"];

const char *insert_stmt = [insertSQL UTF8String];

sqlite3_prepare_v2(dbPointer, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
labelStatus.text = @"added";
}
else
{
labelStatus.text = @"failed";
}

sqlite3_finalize(statement);
sqlite3_close(dbPointer);
}
}

最佳答案

    //your database is not writable because its in the bundle.
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"KJV.sqlite"];


如果您想要一个可读/可写的数据库,则可以执行以下操作:

    - (void) createEditableCopyOfDatabaseIfNeeded 
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"databasename.sqlite"];
NSLog(@"writableDBPath == %@",writableDBPath);
if ([fileManager fileExistsAtPath:writableDBPath])
{
NSLog(@"Database already exist");
}
else
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"databasename.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success)
NSLog(@"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
}


以及您如何添加数据

- (void) addToDatabase
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"databasename.sqlite"];

if(sqlite3_open([databasePath UTF8String], &mDatabase_update) == SQLITE_OK)
{

NSString *sqlQuery = [NSString stringWithFormat: @"Insert into table
.
.
.
.

关于objective-c - SQLite insert语句不会在表中放置记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13982711/

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