【问题标题】:Save Value on Sqlite在 Sqlite 上保存价值
【发布时间】:2016-12-06 21:17:14
【问题描述】:

我正在尝试在 iPhone 应用程序中将值插入我的 sqlite 数据库。在数据库 insertSQL 上插入值显示 nil 值。值未添加到数据库。值未插入创建数据库。第一个函数创建数据库连接,student.db是数据库名称。第二个函数可以输入值并在类上调用函数来保存数据,但insertSQL为nil。所以值不存储在数据库中。但没有成功: 在此先感谢..

代码..

  -(BOOL)createDB{
    NSString *docsDir;
    NSArray *dirPaths;
    // Get the documents directory
    dirPaths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];
    // Build the path to the database file
    databasePath = [[NSString alloc] initWithString:
                                    [docsDir stringByAppendingPathComponent: @"student.db"]];
    BOOL isSuccess = YES;
    NSFileManager *filemgr = [NSFileManager defaultManager];
                    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
     const char *dbpath = [databasePath UTF8String];
     if (sqlite3_open(dbpath, &database) == SQLITE_OK)
     {
     char *errMsg;
     const char *sql_stmt ="create table if not exists studentsDetail (regno integer primary key, name text, department text, year text)";
   if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
                                != SQLITE_OK)
   {
   isSuccess = NO;
   NSLog(@"Failed to create table");
   }
   sqlite3_close(database);
   return  isSuccess;
   }
   else {
   isSuccess = NO;
   NSLog(@"Failed to open/create database");
   }
   }
   return isSuccess;
   }
   - (BOOL) saveData:(NSString*)registerNumber name:(NSString*)name
                       department:(NSString*)department year:(NSString*)year;
   {
   const char *dbpath = [databasePath UTF8String];
   if (sqlite3_open(dbpath, &database) == SQLITE_OK)
   {
   NSString *insertSQL = [NSString stringWithFormat:@"insert into studentsDetail (regno,name, department, year) values(\"%ld\",\"%@\", \"%@\", \"%@\")",(long)[registerNumber integerValue],name, department, year];
   const char *insert_stmt = [insertSQL UTF8String];
   sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
   if (sqlite3_step(statement) == SQLITE_DONE)
   {
    return YES;
   }
   else {
   return NO;
   }
     sqlite3_reset(statement);
   }
    return NO;
   }       
  -(IBAction)Save:(id)sender {
  BOOL success = NO;
  NSString *alertString = @"Data Insertion failed";
            if (_regNo.text .length>0 &&_name.text.length>0 && _department.text.length>0 &&_year.text.length>0){
                success = [[Sqlite getSharedInstance]saveData:
                           _regNo.text name:_name.text department:
                           _department.text year:_year.text];
  }
  else{
   alertString = @"Enter all fields";
  }
  if (success == NO) {
  UIAlertView *alert = [[UIAlertView alloc]initWithTitle:
                                      alertString message:nil
                                      delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
  }
  _regNo.text = @"";
  _department.text = @"";
  _name.text = @"";
  _year.text = @"";

 }

【问题讨论】:

  • 使用 student.sqlite 代替 student.db。

标签: ios objective-c sqlite


【解决方案1】:

我建议您检查一下准备语句是否确实有效...

   if(sqlite3_prepare_v2(database, insert,-1, &statement, NULL) != SQLITE_OK) {
       NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(db), sqlite3_errcode(db));
   }

【讨论】:

    【解决方案2】:

    创建NSObject 类的DBManager

    这是正确的实现:

    static MyDBManager *sharedInstance = nil;
    static sqlite3 *database = nil;
    static sqlite3_stmt *statement = nil;
    
    
    
    @implementation MyDBManager
    +(MyDBManager*)getSharedInstance{
        if (!sharedInstance) {
            sharedInstance = [[super allocWithZone:NULL]init];
            [sharedInstance createDB];
        }
        return sharedInstance;
    }
    
    -(instancetype) init
    {
    
        [self createDB];
    
        return self;
    }
    
    -(BOOL)createDB{
        NSString *docsDir;
        NSArray *dirPaths;
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        docsDir = dirPaths[0];
        // Build the path to the database file
        databasePath = [[NSString alloc] initWithString:
                        [docsDir stringByAppendingPathComponent: @"MyDataBase.db"]];
    
    
        NSLog(@"DataBase path : %@",databasePath);
    
        NSFileManager *filemgr = [NSFileManager defaultManager];
        if ([filemgr fileExistsAtPath: databasePath ] == NO)
        {
            const char *dbpath = [databasePath UTF8String];
            if (sqlite3_open(dbpath, &database) == SQLITE_OK)
            {
                char *errMsg;
      //create section table
                NSString *create_table_section= [NSString  stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@ INTEGER ,%@ TEXT ,%@ TEXT  );",TABLE_SECTION,ID,NAME,MODIFIED_DATE];
      const char *sql_stmt_section =[create_table_section UTF8String];
    
    
       BOOL check=sqlite3_exec(database, sql_stmt_section, NULL, NULL, &errMsg)
                != SQLITE_OK;
     sqlite3_close(database);
    
                return  check;
            }
            else {
                return NO;
                NSLog(@"Failed to open/create database");
            }
        }
        return NO;
    }
    

    创建插入数据的方法

    -(BOOL) insertDropdownValues:(NSString *)tableName
                           andId:(NSInteger) dID
                            name:(NSString*) name
                    modifiedDate:( NSString*) modifiedDate {
    
        const char *dbpath = [databasePath UTF8String];
        if (sqlite3_open(dbpath, &database) == SQLITE_OK)
        {
    
            NSString *insertSQL = [NSString stringWithFormat:@"insert into %@ (%@, %@, %@) values (\"%ld\",\"%@\", \"%@\")",tableName,ID,NAME,MODIFIED_DATE, dID,name,modifiedDate];
    
            const char *insert_stmt = [insertSQL UTF8String];
    
    
            sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
    
    
            if (sqlite3_step(statement) == SQLITE_DONE)
            {
    
                NSLog(@"Inserted SuccessFull");
                              sqlite3_finalize(statement);
                sqlite3_close(database);
    
                return YES;
            }
            else {
    
                NSLog(@"Insertion failed !");
                sqlite3_finalize(statement);
                sqlite3_close(database);
    
                return NO;
            }
    
        }
    
        sqlite3_reset(statement);
        return NO;
    
    }
    

    用途: 将DBManager 类导入你的类而不是

        MyDBManager *dbManager=[[MyDBManager alloc] init];
    
    // create your method that will Accept your parameters and insert into database  
    
    BOOL check=[dbManager insertDropdownValues:@"tableName"
                               andId:@"you_id"
                                name:@"name"
                        modifiedDate:@"your_date" ]
    
    // you can check if data is inserted or not 
    
     if(check)
    {
     // inserted Successful
    }
    else
    {
      // couldn't insert data 
    }
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-01-01
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多