简体   繁体   English

数据未插入sqlite数据库

[英]Data not inserting into sqlite database

Hi in my application I have data which want insert into my sqlite database .So I have already created the database successfully, But the problem its not insert data into database. 嗨,在我的应用程序中,我有想要插入到我的sqlite数据库中的数据。因此,我已经成功创建了数据库,但是问题是它没有将数据插入到数据库中。

My database creation code. 我的数据库创建代码。

 - (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"];
      }
   }
 }

My insert code i have UIButton action method where i give my insert code. 我的插入代码我有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);
 }

I have used the above code where get the data and inserting into my database but values all passing correctly problem is its not inserting into my database please tell me how to resolve this issue I have been stuck here for long time help me out. 我在上面的代码中使用了获取数据并将其插入到我的数据库中的方法,但是所有正确传递值的问题是它没有插入到我的数据库中,请告诉我如何解决此问题。

Thanks. 谢谢。

When i saw your question, i couldn't help seeing something that was a bit strange to me... and that was seeing my own code. 当我看到您的问题时,我不禁看到一些对我来说有点奇怪的东西……那是在看我自己的代码。 thanks for using my code snippet from stackoverflow :) getting error while trying to create sqlite database 'Could not create table' IOS7 感谢您使用我来自stackoverflow的代码片段:) 尝试创建sqlite数据库“无法创建表” IOS7时出错

Any way, here is a quick example on how to insert: 无论如何,这是一个有关如何插入的快速示例:

- (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);
        }
    }
}

try this code... 试试这个代码...

-(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);
}

DBmanager.h file 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 file 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;
        }

Call DBmanager 致电DBmanager

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM