我想插入數據到我的SQLite數據庫。我導入了所有爲我的項目而定的neccassry框架和數據庫文件。在我的控制器類xib中有兩個文本框和一個按鈕。當我點擊按鈕時,我希望將數據輸入保存在數據庫中的兩個文本字段中。從文本字段插入數據到SQLite數據庫
在我的應用程序delagate中,我創建了兩個函數,一個函數用於追加數據庫的路徑,另一個用於將數據插入數據庫。在插入功能中,我檢查某些條件,即如果添加了數據,應該顯示一個警告視圖,顯示添加的記錄,但是當我添加新記錄時,它總是進入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];
}
請解決此問題。
........可能的重複http://stackoverflow.com/questions/5699025/how-to-insert-data-in-sqlite-database/ 5699047#5699047 – Jhaliya 2011-04-18 08:48:22
我關閉了你之前的問題,因爲這個包含更多的信息。但是,將來只需編輯您的問題以提供更多信息。 – 2011-04-21 06:16:28