我有app在其中我在sqlite表中插入数据我希望如果数据已经插入那么它不应该插入相同的记录这里是我的插入数据的代码。
这里是带插入语句的代码,用于插入数据
- (void) addCoffee:(NSString *)dbPath {
if(addStmt == nil) {
const char *sql = "insert into library(userID,contentAddedDateTime,contentType,contentTitle,contentSource,contentDescription,categoryTitle,subCategoryTitle,organizationCode,userName) Values(?,?,?,?,?,?,?,?,?,?)";
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_text(addStmt, 1, [userID UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 2, [contentAddedDateTime UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [contentType UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 4, [contentTitle UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 5, [contentSource UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 6, [contentDescription UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 7, [categoryTitle UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 8, [subCategoryTitle UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 9, [organizationCode UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 10, [userName UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
coffeeID = sqlite3_last_insert_rowid(database);
//Reset the add statement.
sqlite3_reset(addStmt);
}
答案 0 :(得分:0)
您应该使用唯一列编写选择查询。在你的案例中说 userID
const char * sql =“select * from library where userID =%@”;
如果存在记录而不是输入else skip
答案 1 :(得分:0)
- (int) GetCount :(NSString *)UserID
{
[self createEditableCopyOfDatabaseIfNeeded];
[self initializeDatabase];
int count = 0;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"dbfav2table.sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *statement;
NSString *sql_str = [NSString stringWithFormat:@"SELECT count(*) FROM tablename WHERE userID='%@'", UserID];
const char *sqlStatement = (char *)[sql_str UTF8String];
NSLog(@"%@", [NSString stringWithUTF8String:sqlStatement]);
if( sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
{
while( sqlite3_step(statement) == SQLITE_ROW )
{
count = sqlite3_column_int(statement, 0);
NSLog(@"count for %@ is %i",UserID,count);
}
}
else
{
NSLog( @" Error is: %s", sqlite3_errmsg(database) );
}
// Finalize and close database.
sqlite3_finalize(statement);
sqlite3_close(database);
}
return count;
}
如果返回count = 1,则表示已存在具有相同userId的值,否则没有此值。希望它有所帮助