我正在从数据库中删除记录。它工作正常。但是,当数据库中没有数据时,它会崩溃。代码如下

 int noOfRecordsDeleted;

     [self openDatabaseConnection];

    //  query = [NSString stringWithFormat:@"delete from %@ where %@",query];
    NSLog(@"del query=%@",query);
    const char *sql = [query cStringUsingEncoding:NSUTF8StringEncoding];
    sqlite3_stmt *statement = nil;

    if(sqlite3_prepare_v2(dataBaseConnection,sql, -1, &statement, NULL)!= SQLITE_OK)
    {
                                   NSAssert1(0,@"error preparing statement",sqlite3_errmsg(dataBaseConnection));
    }



    else
    {
        int success = sqlite3_step(statement);
        NSLog(@"%d",success);
    }
    sqlite3_finalize(statement);
      noOfRecordsDeleted = sqlite3_changes(dataBaseConnection);
   [self closeDatabaseConnection];
    return noOfRecordsDeleted;


一切正常。但是,如果我要添加数据,则我的数据库为空,这将导致崩溃

[self openDatabaseConnection];

NSString *query;

query = [NSString stringWithFormat:@"insert into Userdetail(aboutMe,anniversary,areacode,birthdate,device_id,chat_id,emailid,gender   ,image,last_login,latitute,longitude,Looking_For,mobilenumber,mobilenumber1          ,mobilenumber2,mood,name,password,place,profileviews,statusmessage) values ('%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",aboutMe,anniversarydate,areacode,birthdate,
    device_id,chat_id,email_id,gender,image,last_login,latitude,longitude,looking_for,mobilenumber,mobilenumber1,mobilenumber2,mood,name,password,place,profileviews,statusmessage];

NSLog(@"saveNewTemplateData query=%@",query);
const char *sql = [query cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *statement = nil;if(sqlite3_prepare_v2(dataBaseConnection,sql , -1, &statement, NULL)!= SQLITE_OK)
{
    NSAssert1(0,@"error preparing statement",sqlite3_errmsg(dataBaseConnection));
}
else
{
    sqlite3_step(statement);
}
sqlite3_finalize(statement);
[self closeDatabaseConnection];


以上是代码

最佳答案

首先使用以下语句检查数据库是否为空

if(sqlite3_column_text(statement, 0) != nil){//Data exists}


然后在if方法中添加代码以删除数据库。
它工作正常。

关于ios - 从SQLite的空数据库中删除,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20882930/

10-09 07:04
查看更多