0
- (void)viewDidLoad {
// Do any additional setup after loading the view, typically from a nib.
NSString *docsDir;
NSArray *dirPaths;
dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
docsDir =[dirPaths objectAtIndex:0];
databasePath=[[NSString alloc]initWithString: [docsDir stringByAppendingString:@"test2.db"]];
//databasePath=[NSString stringWithFormat:[docsDir stringByAppendingPathComponent:@"test2.db"]];
NSFileManager *filemgr=[NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath] ==NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &test2DB) ==SQLITE_OK)
{
char *errMSg;
const char *sql_stmt= "CREATE TABLE IF NOT EXISTS TESTING (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRSTNAME TEXT, LASTNAME TEXT, EMAIL TEXT, ADDRESS TEXT)";
if (sqlite3_exec(test2DB, sql_stmt, NULL, NULL, &errMSg) != SQLITE_OK)
{
[email protected]"Failed To Create Table";
}
sqlite3_close(test2DB);
}else{
status.text [email protected]"Failed to open/create database";
}
}
[super viewDidLoad];
}
//保存數據如何使用sqlite數據庫插入數據?
-(IBAction)save:(id)sender
{
sqlite3_stmt *statment;
const char *dbpath =[databasePath UTF8String];
if (sqlite3_open(dbpath, &test2DB) ==SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO TESTING(Firstname,Lastname,Email,Address) VALUES (\"%@\", \"%@\", \"%@\", \%@\")",Firstname.text,Lastname.text,Email.text,Address.text];
const char *insert_stmt=[insertSQL UTF8String];
sqlite3_prepare_v2(test2DB, insert_stmt, -1, &statment, NULL);
if (sqlite3_step(statment) ==SQLITE_DONE) {
[email protected]"Details Added";
[email protected]"";
[email protected]"";
[email protected]"";
[email protected]"";
}else
{
[email protected]"Failed to Add Details";
}
sqlite3_finalize(statment);
sqlite3_close(test2DB);
}
}
我已經完成了這段代碼,但值不會被保存。如果我運行的代碼沒有錯誤將顯示。但如果我輸入數據,然後單擊保存按鈕的數據將不會被保存。如果我運行代碼「無法添加詳細信息」的消息將顯示在模擬器上。猜猜錯誤在哪裏。 –
你是否改變了這一行sqlite3_finalize(statement); sqlite3_close(test2);在你的代碼 –
它的工作與否? –