在sqlite表中插入大量文本的问题

时间:2014-12-08 08:28:18

标签: ios mysql objective-c sqlite

我想在我的sqlite表中插入文本,它包含大量(大约1000个字符) 这是我的代码

//创建功能

    //createdb here
    if (sqlite3_open([dbPathString  UTF8String], &database)==SQLITE_OK) {
        const char *sql_stmt="CREATE TABLE IF NOT EXISTS mytablename(description TEXT)";
        sqlite3_exec(database, sql_stmt, NULL, NULL, &error);
        sqlite3_close(database);

    }

//插入

  for (int i=0; i<_generalContentArray.count; i++) 
 {
   char *error;
  if (sqlite3_open([dbPathString UTF8String], &database)==SQLITE_OK) 

 {
   NSString *query=[NSString stringWithFormat:@"INSERT INTO mytablename(description)    values('%@')",[[_generalContentArray objectAtIndex:i]objectForKey:@"description"]];

      const char *insert_stmt=[query UTF8String];
       if (sqlite3_exec(database, insert_stmt, NULL, NULL, &error )==SQLITE_OK)
          {
                 NSLog(@"Text added");

          }
        else
          {
                 NSLog(@"Text not added");

          }

                sqlite3_close(database);
   }
 }

我的问题是它从不执行SQLITE_OK语句并且总是转到else语句,文本没有添加到我的表中,请帮忙

1 个答案:

答案 0 :(得分:0)

你必须检查db是否存在。不是这个......

for (int i=0; i<_generalContentArray.count; i++)
    {
        char *error;
        //you need to check db is exising or not
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"your db name"];
        if (sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK)

        {
            NSString *query=[NSString stringWithFormat:@"INSERT INTO mytablename(description)    values('%@')",[[_generalContentArray objectAtIndex:i]objectForKey:@"description"]];

            const char *insert_stmt=[query UTF8String];
            if (sqlite3_exec(database, insert_stmt, NULL, NULL, &error )==SQLITE_OK)
            {
                NSLog(@"Text added");

            }
            else
            {
                NSLog(@"Text not added");

            }

            sqlite3_close(database);
        }
    }

像这样更改您的查询...

 NSString *query=[NSString stringWithFormat:@"INSERT INTO mytablename('description') VALUES('%@')",[[_generalContentArray objectAtIndex:i]objectForKey:@"description"]];
相关问题