如何在目标c中的SQL Lite中插入数据?

时间:2017-03-21 09:19:06

标签: ios objective-c iphone ios10

我试图插入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

1 个答案:

答案 0 :(得分:2)

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

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

Files in the app bundle are read only。您需要先copy the database elsewhere,例如打开文档文件夹之前。

请注意,您应使用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) {
    ...