数据未插入sqlite数据库

时间:2014-06-23 11:40:55

标签: ios ios7 sqlite insert

您好我的应用程序中有数据要插入我的sqlite数据库。所以我已经成功创建了数据库,但问题是它没有将数据插入数据库。

我的数据库创建代码。

 - (void)createDatabase
  {

     NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *doctumentsDirectory = [directories lastObject];
     self.databasePath = [[NSString alloc] initWithString:[doctumentsDirectory stringByAppendingPathComponent:@"/bp.sqlite"]];

     NSFileManager *fileManager = [NSFileManager defaultManager];

   // create DB if it does not already exists
   if (![fileManager fileExistsAtPath:self.databasePath]) {

       const char *dbPath = [self.databasePath UTF8String];

    if (sqlite3_open(dbPath, &_myDataBase) == SQLITE_OK) {

        char *errorMsg;
        const char *sql_statement = "CREATE TABLE IF NOT EXISTS br (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, COST TEXT,QUTY TEXT)";

        if (sqlite3_exec(_myDataBase, sql_statement, NULL, NULL, &errorMsg) != SQLITE_OK)    {

            [self errorCreatingTable:[NSString stringWithFormat:@"failed creating table. ERROR:%s", errorMsg]];
         }

          sqlite3_close(_myDataBase);

      } else {

         [self errorCreatingTable:@"failed openning / creating table"];
      }
   }
 }

我的插入代码我有UIButton动作方法,我给出了我的插入代码。

  -(void)aMethod2:(UIButton*)sender
 {

    NSString *inr=[intarr objectAtIndex:sender.tag];
    NSLog(@"%@",inr);
    NSString *item=[self.menuarray objectAtIndex:sender.tag];
    NSLog(@"%@",item);
    NSString *cost=[self.menuarray1 objectAtIndex:sender.tag];
    NSLog(@"%@",cost);
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO br ('NAME','COST','QUTY') VALUES ('%@','%@','%@')",item,cost,inr];
    NSLog(@"%@",sql);
 }

我已经使用上面的代码获取数据并插入到我的数据库但是所有传递正确的值问题是它没有插入我的数据库请告诉我如何解决这个问题我已经被困在这里很长时间帮助我

感谢。

3 个答案:

答案 0 :(得分:5)

当我看到你的问题时,我忍不住看到一些对我来说有点奇怪的东西......那就是看到我自己的代码。感谢您使用stackoverflow :) getting error while trying to create sqlite database 'Could not create table' IOS7

中的代码片段

无论如何,这里有一个关于如何插入的简单示例:

- (void)insertDictionaryToDataBase:(NSDictionary *)dictionary
{
    if (dictionary) {

        sqlite3_stmt *sql_statement;
        const char *dbPath = [self.databasePath UTF8String];

        if (sqlite3_open(dbPath, &_inboxDatabase) == SQLITE_OK) {

            NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO MY_TABLE_NAME (COLUMN_A, COLUMN_B, COLUMN_C) VALUES (?,?,?)"];

            const char *insertStatement = [insertSQL UTF8String];

            sqlite3_prepare_v2(_inboxDatabase, insertStatement, -1, &sql_statement, NULL);

            sqlite3_bind_text(sql_statement, 1, [dictionary[@"key1"] UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(sql_statement, 2, [dictionary[@"key2"] UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_int(sql_statement, 3, [dictionary[@"key3"] intValue]);


            if (sqlite3_step(sql_statement) == SQLITE_DONE) {

                NSLog(@"sucess!");
            }

            sqlite3_finalize(sql_statement);
            sqlite3_close(_inboxDatabase);
        }
    }
}

答案 1 :(得分:1)

试试这段代码......

-(void)Insertdata:(NSString*)query{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"bp.sqlite"];
    NSLog(@"%@",databasePath);
    if(sqlite3_open([databasePath UTF8String],&_myDataBase) == SQLITE_OK)
    {
        NSString *querySQL = [NSString stringWithFormat: @"%@",query];

        char *errmsg=nil;

        if(sqlite3_exec(_myDataBase, [querySQL UTF8String], NULL, NULL, &errmsg)==SQLITE_OK)
        {
            NSLog(@".. Inserted ..");
        }
    }
    sqlite3_close(_myDataBase);
}

答案 2 :(得分:0)

DBmanager.h文件

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface DBReadWriteUtil : NSObject

+(sqlite3*)copyDbToDocumentsDirectoryIfNotExist;
+(BOOL)insertData:(NSString*)arg1 cost:(int)arg2 quty:(int)arg3;
+(NSDictionary*)getUploadPendingMedia;
+(int)removeMediaPOStFormId:(int)row_id;
@end

DBmanager.m文件

#import "DBReadWriteUtil.h"

@implementation DBReadWriteUtil

+(sqlite3*)copyDbToDocumentsDirectoryIfNotExist{

    NSString *dbPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"bp.sqlite"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:dbPath]) {
        NSString *localDB = [[NSBundle mainBundle] pathForResource:@"bp" ofType:@"sqlite"];
        NSError *err;
        if(![fileManager copyItemAtPath:localDB toPath:dbPath error:&err]){
            if (DEBUG_MODE) {
             NSLog(@"SQL: Not ABLE TO COPY FILE -> %@",err);   
            }
        }
    }
    sqlite3 *db_connction;
    if(sqlite3_open([dbPath UTF8String], &db_connction) != SQLITE_OK){
        if (DEBUG_MODE) {
            NSLog(@"SQL : Not ABLE TO CONNECT DB:");
        }
    }
    return db_connction;
}

+(BOOL)insertData:(NSString*)arg1 cost:(int)arg2 quty:(int)arg3{
           BOOL dbStatus = NO;
            sqlite3 *db_connction = [DBReadWriteUtil copyDbToDocumentsDirectoryIfNotExist];
            sqlite3_stmt *compiledStmt;
            const char *query = "insert into br(NAME,cost,quay) values(?,?,?)";
            if(sqlite3_prepare_v2(db_connction, query, -1, &compiledStmt, NULL) == SQLITE_OK ){
                sqlite3_bind_text(compiledStmt,1,[arg1 UTF8String],-1,SQLITE_TRANSIENT);
                sqlite3_bind_int(compiledStmt, 2, arg2);
                sqlite3_bind_int(compiledStmt,3, arg3,-1);

                NSUInteger err = sqlite3_step(compiledStmt);
                if (err != SQLITE_DONE){
                    if(DEBUG_MODE){
                        NSLog(@"error while Inserting image %d %s",err, sqlite3_errmsg(db_connction));
                    }
                }else{
                    dbStatus = YES;
                }
            }
            sqlite3_finalize(compiledStmt);
            sqlite3_close(db_connction);

            return dbStatus;
        }

致电DBmanager

BOOL successDB = [DBReadWriteUtil insertData: arg1 cost:arg2 quty:arg3];