【问题标题】:How to insert data in SQL Lite in objective c?如何在目标 c 中的 SQLite 中插入数据?
【发布时间】:2017-08-12 20:45:13
【问题描述】:

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

代码如下:

我已经拿了两本教科书,点击那个按钮就可以完成。

这是我的 .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

【问题讨论】:

标签: ios objective-c iphone ios10


【解决方案1】:

插入失败,因为您直接使用了存储在 app bundle 中的数据库。

[[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) {
    ...

【讨论】:

    猜你喜欢
    • 2011-12-13
    • 2012-08-27
    • 2023-04-04
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多