How can I delete all rows from a table in an SQLite database in one step (not one by one)?
6 Answers
SQLite Documentation. Deletion of rows in iOS :
NSString *query = @"delete from yourTable";
const char *sqlStatement = [query UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSLog(@"result is here");
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
Comments
(void) DeleteRows {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath =[documentsDir stringByAppendingPathComponent:@"gym.db"];
BOOL success = [fileManager fileExistsAtPath:dbPath];
sqlite3_stmt *selectstmt;
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"gym.db"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
if (sqlite3_open([dbPath UTF8String], &contactDB) == SQLITE_OK) {
//*************** insert value in database******************************\\
NSString *sql = [NSString stringWithFormat:@"delete from Offers"];
const char *insert_stmt = [sql UTF8String];
sqlite3_prepare_v2(contactDB,insert_stmt, -1, &selectstmt, NULL);
if(sqlite3_step(selectstmt)==SQLITE_DONE)
{
NSLog(@"Delete successfully");
}
else
{
NSLog(@"Delete not successfully");
}
sqlite3_finalize(selectstmt);
sqlite3_close(contactDB);
}
}
Comments
- (IBAction)deleteAll:(id)sender {
NSString *tableName=@"Contacts";
NSString *qsql = [NSString stringWithFormat:@"DELETE FROM %@",
tableName];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2( db, [qsql UTF8String], -1,
&statement, NULL) == SQLITE_OK)
while (sqlite3_step(statement) == SQLITE_DONE){
NSLog(@"%@", @"deleted");
}
else {
sqlite3_close(db);
NSAssert(0, @"Failed to Delete");
}
sqlite3_finalize(statement);
}
Comments
In Swift you can do it like this:
let tableName = "myTable"
let deleteStatementString = "DELETE FROM \(tableName);"
var deleteStatement: OpaquePointer? = nil
if sqlite3_prepare_v2(db, deleteStatementString, -1, &deleteStatement, nil) == SQLITE_OK {
if sqlite3_step(deleteStatement) == SQLITE_DONE {
print("Successfully deleted all rowns from \(tableName)")
} else {
print("Could not delete all rowns from \(tableName)")
}
} else {
print("DELETE statement could not be prepared")
}
sqlite3_finalize(deleteStatement)