状态:有时app会顺畅运行并在tableview中显示数据库中的数据。当我重建或重新启动..
所有数据都消失了。
我有三个文本字段和一个保存数据的按钮。
查看控制器:两个tableviews
使用tableviewcontroller
,另一个使用tableview delegate
方法..我的代码在这里
-(IBAction)addTextToDatabase:(id)sender
{
sqlite3_stmt * statement;
char const * dbpath = [databasepath UTF8String];
if (sqlite3_open(dbpath, &myDatabase) == SQLITE_OK)
{
NSString * insertSQL = [NSString stringWithFormat:@"INSERT INTO income (category, price, date) values (\"%@\", \"%@\", \"%@\")", self.categoryTextField.text,self.priceTextField.text,self.dateTextField.text];
const char * insert_stmt = [insertSQL UTF8String];
NSLog(@"%@",insertSQL);
sqlite3_prepare_v2(myDatabase, insert_stmt,-1, &statement, NULL);if (sqlite3_step(statement)== SQLITE_DONE)
{
statusOfAddingToDB = [NSString stringWithFormat:@"Text Added - %@ %@ %@",self.categoryTextField.text,self.priceTextField.text,self.dateTextField.text];
}
else
{
statusOfAddingToDB = @"Failed to Insert Databsae";
NSLog(@"%d",SQLITE_ERROR);
NSLog(@"sqlite3_step error: '%s'", sqlite3_errmsg(myDatabase));
}
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"DB status" message:statusOfAddingToDB delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil];
[alert show];
sqlite3_finalize(statement);
sqlite3_close(myDatabase);
}
}
- (void)prepareDatabase
{
// Get the documents directory
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = dirPaths[0];
// Build the path to the database file
databasepath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"expenseSystem.db"]];
NSLog(@"DB Path: %@", databasepath);
NSFileManager * filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasepath ] == NO) {
const char *dbpath = [databasepath UTF8String];
if (sqlite3_open(dbpath, &myDatabase) == SQLITE_OK) {
char *errMsg;
NSLog(@"%s",errMsg);
const char *sql_stmt ="CREATE TABLE IF NOT EXISTS income (id INTEGER PRIMARY KEY AUTOINCREMENT, category TEXT , price TEXT, date TEXT)";
if (sqlite3_exec(myDatabase, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) {
statusOfAddingToDB = @"Failed to create table";
} else {
statusOfAddingToDB = @"Success in creating table";
NSLog(@"%@",myDatabase);
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DB Status" message:statusOfAddingToDB delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
sqlite3_close(myDatabase);
} else {
statusOfAddingToDB = @"Failed to open/create database";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DB Status" message:statusOfAddingToDB delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
}
}
出现错误
没有表收入