gpt4 book ai didi

ios - 如何在 Objective C 中的 SQLite 中插入数据?

转载 作者:行者123 更新时间:2023-11-28 21:11:33 26 4
gpt4 key购买 nike

我正在尝试插入 2 个文本框的值,即用户 ID 和密码。但我没有收到任何错误或异常。

代码如下:

我已经学习了 2 本教科书,我正在点击那个按钮来学习。

这是我的 .m 文件:

#import "ViewController.h"
#import "sqlite3.h"
#import <CommonCrypto/CommonCryptor.h>
NSString *databasePath;
NSString *docsDir;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
@interface ViewController ()
@end
@implementation ViewController
@synthesize status,status2;

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)saveData:(id)sender{

databasePath = [[NSBundle mainBundle]pathForResource:@"ButterFly2BE" ofType:@"db"];
NSString *p=@"PAss";
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &adddata) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
@"INSERT INTO tblUser (UserId,Password,Description) VALUES(\"%@\",\"%@\",\"%@\")"
, _username.text, _password.text, p];


const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(adddata, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
status.text = @"Contact added";
// status.text = @"";
status2.text = @"";
// phone.text = @"";
} else {
status.text = @"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(adddata);
}
}
@end

最佳答案

插入失败,因为您直接使用了存储在应用程序包中的数据库。

[[NSBundle mainBundle] pathForResource:@"ButterFly2BE" ofType:@"db"]

Files in the app bundle are read only .你需要先copy the database elsewhere例如Documents 文件夹,然后再打开它。


请注意,您应该使用 the sqlite3_bind_xxxx functions而不是 -stringWithFormat: 因为后者会让你看到 SQL injection attack .

sqlite3_prepare_v2(adddata, 
"INSERT INTO tblUser (UserId, Password, Description) VALUES (?, ?, ?);",
-1, &statement, NULL);
sqlite3_bind_text(statement, 1, _username.text.UTF8String, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 2, _password.text.UTF8String, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 3, p.UTF8String, -1, SQLITE_TRANSIENT);
if (sqlite3_step(statement) == SQLITE_DONE) {
...

关于ios - 如何在 Objective C 中的 SQLite 中插入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42922805/

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