Я пытаюсь вставить данные в базу данных SQLite. Я импортировал все необходимые структуры и файлы базы данных для моего проекта. В моем контроллере класса xib есть два текстовых поля и кнопка. Я хочу, чтобы данные, введенные в оба текстовых поля, сохранялись в моей базе данных при нажатии на кнопку.
В моем приложении я создал две функции: одну для добавления пути к базе данных, а другую для вставки данных в базу данных. В функции вставки я проверяю наличие определенных условий, т. Е. Если данные добавляются, должно отображаться окно с предупреждением, показывающее добавленную запись, но при добавлении новой записи она всегда переходит в блок else
, что является ошибкой .
-(void)checkAndCreateDB {
NSString* databaseName = @"login.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:@"login.sqlite"];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(void)insertData{
sqlite3 *database;
sqlite3_stmt *statement;
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
NSString *databasePath=[documentsDir stringByAppendingPathComponent:@"login.sqlite"];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO Loginchk (uname,password) VALUES ('%@',' %@');",Gunameq,Gpassq];
const char *insert_stmt = [insertSQL UTF8String];
if(sqlite3_prepare_v2(database, insert_stmt, -1, &statement, nil)== SQLITE_OK)
{
sqlite3_bind_text(statement, 1, [Gunameq UTF8String], -1, NULL);
sqlite3_bind_text(statement, 2, [Gpassq UTF8String], -1, NULL);
}
if(sqlite3_step(statement)==SQLITE_DONE)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add Record" message:@"Contact Added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"record" message:@"record not created" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
// Release the compiled statement from memory
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
Это мой класс контроллера входа в систему. Здесь я объявил функцию, через которую я получаю доступ к функциям моего приложения.
-(IBAction)buttonPressed:(id)sender
{
Gpassq=Password.text;
Gunameq=Uname.text;
NSLog(@"%@%@",Gunameq,Gpassq);
AddListAppDelegate *appDelegate =(AddListAppDelegate *)[[UIApplication sharedApplication]delegate];
[appDelegate insertData];
}
Пожалуйста, решите эту проблему.