2017-03-21 3 views
0

ユーザーIDとパスワードである2つのテキストボックスの値を挿入しようとしています。 しかし、私はエラーまたは例外を取得していません。SQL Liteに客観的なCでデータを挿入するには?

コードは次のように:

私は2教科書をとっていると私はそのボタンのクリックでそれをやっています。あなたが直接アプリケーションバンドルに格納されているデータベースを使用しているため

#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 *[email protected]"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 
+0

あなたはどんな問題に直面していますか?データが挿入されていない...右か? SQLクエリをログに記録し、[DB browser for SQLite](http://sqlitebrowser.org/)を使用してデータベースを開きます。 – Poles

+0

このリンクを参照すると、回答が見つかりますhttp://stackoverflow.com/questions/17080018/use-and-access-existing-sqlite-database-on-ios/39536484#39536484 – Indrajeet

+0

[データの挿入方法iPhoneのSQLiteデータベース](http://stackoverflow.com/questions/2184861/how-to-insert-data-into-a-sqlite-database-in-iphone) – kb920

答えて

2

挿入に失敗しました:

これは私の.mファイルがあります。

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

。最初にcopy the database elsewhereにする必要があります。それを開く前にDocumentsフォルダを開きます。


後者はSQL injection attackにあなたを公開するので、あなたはthe sqlite3_bind_xxxx functions代わりの-stringWithFormat:を使用する必要があります注意してください。

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) { 
    ... 
関連する問題