数据未插入 sqlite 数据库

Posted

技术标签:

【中文标题】数据未插入 sqlite 数据库【英文标题】:Data not inserting into sqlite database 【发布时间】:2014-06-23 11:40:54 【问题描述】:

嗨,在我的应用程序中,我有数据要插入到我的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);
 

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

谢谢。

【问题讨论】:

aMethod2在哪里访问数据库? @CL。这是我的 uibutton aciton 方法 【参考方案1】:

当我看到你的问题时,我忍不住看到了一些对我来说有点奇怪的东西……那就是看到我自己的代码。感谢您使用我来自 *** 的代码 sn-p :) 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);
        
    

【讨论】:

【参考方案2】:

试试这个代码...

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

【讨论】:

【参考方案3】:

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;
        

调用数据库管理员

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

【讨论】:

以上是关于数据未插入 sqlite 数据库的主要内容,如果未能解决你的问题,请参考以下文章

URL 未插入 SQLite3 数据库

SQLite 数据插入未反映在表中

数据未使用 php 插入 sqlite3 数据库

在 Proguard 构建中未使用脚本插入 Sqlite 数据库

CoreData:从字典数组插入到SQLite数据库中发生未排序 - 因此无法设置外键

在单击按钮时将数据插入 Android Studio 中的 SQlite 数据库