这是我的代码:
为了创建数据库,在我的 ViewDidLoad 中:
NSString *docsDir;
NSArray *dirPaths;
dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];
NSFileManager *filemgr=[NSFileManager defaultManager];
if ([filemgr fileExistsAtPath:databasePath]==NO)
{
NSLog(@"Creating DB");
const char *dbpath=[databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
{
char *error_msg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, URL TEXT, EMAIL TEXT, CODE TEXT, FULL TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &error_msg) != SQLITE_OK)
{
NSLog(@"Failed to create table");
}
sqlite3_close(contactDB);
} else {
NSLog(@"Failed to open/create database");
}
} else {
NSLog(@"DB exists");
}
我可以看到输出消息"Creating DB"
然后我必须在那里添加我的数据,我确实有:
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CONTACTS (url, email, code, full) VALUES (\"%@\", \"%@\", \"%@\", \"%@\")", url_2, mail, keycode,full_2 ];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(@"Contact added");
} else {
NSLog(@"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
} else {
NSLog(@"PROBLEM - CONTACT NOT ADDED");
}
我看到了"PROBLEM - CONTACT NOT ADDED"
消息。
有什么帮助吗?