如何在iOS 7中防止SQLite3中的重复数据?

时间:2014-08-05 09:14:19

标签: ios objective-c sqlite

我正在尝试阻止SQlite DB中的重复值。这些实际上是一个名称列表以及我将日期存储为NSString。现在我想要做的是,只插入一次名称如果第二次插入我想更新它的日期?到目前为止我能够插入新记录,但无法更新它。我错过了什么?

 -(NSString *)viewDataBaseForCity:(NSString *)cityName addedDate:(NSString *)dateAdded{

const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK)
{
    NSString *querySQL = [NSString stringWithFormat:@"SELECT cityname FROM CITIES WHERE cityname=%@", cityName];
    const char *query_stmt = [querySQL UTF8String];

    if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL)== SQLITE_OK)
    {
         //This part is not executed at all               

        if (sqlite3_step(statement)==SQLITE_ROW)
        {
            self.tempcityName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
            NSLog(@"Found city name : -%@",self.tempcityName);
            return self.tempcityName;

        }else{

            NSLog(@"Not Found");
            return nil;
        }

        sqlite3_finalize(statement);
        sqlite3_close(citiesDB);
    }

}
return nil;

 }

 -(void)checkforupdate:(NSString *)cityName addedDate:(NSString *)dateAdded{
 {
if(tempcityName == cityName)
{
    NSString *querySQL = [NSString stringWithFormat:@"UPDATE CITIES set id=%@ WHERE cityname=%@", dateAdded, cityName];

    const char *query_stmt = [querySQL UTF8String];
    if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)

    {
        NSLog(@"updated successfully");
    }


    sqlite3_finalize(statement);
    sqlite3_close(citiesDB);
}
else
{
    [self insertintotable:cityName addedDate:dateAdded];
}
}
}

 -(void)insertintotable:(NSString *)cityName addedDate:(NSString *)dateAdded{
 {

    const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK)
    {

        NSString *insert_sql = [NSString stringWithFormat:@"INSERT INTO CITIES(cityname,id)VALUES (\"%@\",\"%@\")",cityName,dateAdded];


        const char *insert_stmt = [insert_sql UTF8String];
        sqlite3_prepare_v2(citiesDB, insert_stmt, -1, &statement, NULL);

        if (sqlite3_step(statement)==SQLITE_DONE)
        { 
            NSLog(@"Saved");      

        }
        else{
            NSLog(@"NOT Saved");    

        }
        sqlite3_finalize(statement);
        sqlite3_close(citiesDB);
}
}

}

现在,表格的字段创建如下。

  - (void)initDatabase{

//Putting in caches

NSString *cacheDir = [NSSearchPathForDirectoriesInDomains
                      (NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
databasePath = [cacheDir
                    stringByAppendingPathComponent:@"CityList.db"];

NSFileManager *filemgr = [NSFileManager defaultManager];



if ([filemgr fileExistsAtPath:databasePath]==NO) {
    const char *dbpath = [databasePath UTF8String];

    if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK) {


        char *errMsg;
        NSString *sql_stmt = @"CREATE TABLE IF NOT EXISTS CITIES (";

        sql_stmt = [sql_stmt stringByAppendingString:@"cityname TEXT PRIMARY KEY UNIQUE, "];

        sql_stmt = [sql_stmt stringByAppendingString:@"id TEXT)"];

        if (sqlite3_exec(citiesDB, [sql_stmt UTF8String], NULL, NULL, &errMsg)!=SQLITE_OK)   {

            NSLog(@"Failed to create table");

        }
        else
        {
            NSLog(@"CITIES table created successfully");
        }

        sqlite3_close(citiesDB);

    }else {

        NSLog(@"Failed to open/create database");
    }
   }

   }

3 个答案:

答案 0 :(得分:0)

首先尝试更新日期。 如果失败(即,如果sqlite3_changes表示没有修改任何行),请插入一个新行:

execute("UPDATE Cities SET id = ? where cityname = ?", ...);
if (sqlite3_changes(citiesDB) == 0) {
    execute("INSERT INTO Cities(cityname, id) VALUES(?,?)", ...);
}

答案 1 :(得分:0)

首先,您使用Retrieve Query从表中检索名称的所有数据。

  if ([RetriveDat containsObject:@"New Data"])
      {    
         // Update Quert
      }
    else
      {
         // Insert Query
      }

答案 2 :(得分:0)

以下代码可帮助您完成所需操作。首先检查您输入的城市名称是否存在于数据库表中,然后更新(如果不存在)只需插入数据库表。

@synthesis tempcityName;

-(BOOL)saveCity:(NSString *)cityName addedDate:(NSString *)dateAdded{

sqlite3_stmt *statement;

const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK)
{
    NSString *querySQL = [NSString stringWithFormat:@"SELECT cityname FROM CITIES WHERE cityname=%@", cityName];
    const char *query_stmt = [querySQL UTF8String];

    if (sqlite3_prepare_v2(citiesDB, query_stmt, -1, &statement, NULL)== SQLITE_OK)
    {
        if (sqlite3_step(statement)==SQLITE_ROW)
        {
            tempcityName = [[NSString alloc]initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];

        }

        else{
        [self.insertintotable:cityName];
        }

        sqlite3_finalize(statement);
    }
    sqlite3_close(citiesDB);
[self.checkforupdate:cityName];
}

检查数据是否有资格更新:

-(void)checkforupdate:(NSString *)cityName
{
if(tempcityName == cityName)
{
NSString *querySQL = [NSString stringWithFormat:@"UPDATE CITIES set id=%@ WHERE cityname=%@", dateAdded, cityName];

const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(_beaconDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)

{
NSLog(@"updated successfully");
}

sqlite3_finalize(query_stmt);
sqlite3_close(citiesDB);
}
else
{
[self.insertintotable:cityName];
}
}

如果数据不符合更新条件,则调用插入数据库表

-(void)insertintotable:(NSString *)cityName
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &citiesDB)==SQLITE_OK) {


//This inserts same name multiple times.
NSString *insert_sql = [NSString stringWithFormat:@"INSERT INTO CITIES(cityname,id)VALUES (\"%@\",\"%@\")",cityName,dateAdded];


const char *insert_stmt = [insert_sql UTF8String];
sqlite3_prepare_v2(citiesDB, insert_stmt, -1, &statement, NULL);

if (sqlite3_step(statement)==SQLITE_DONE) 
{ 
NSLog(@"Saved");      
return YES;
}
else{
NSLog(@"NOT Saved");    
return NO;
}
sqlite3_finalize(statement);
sqlite3_close(citiesDB);
}