我在我的iOS應用程序中使用SQLite數據庫。在我的屏幕1中,我成功地創建了一個數據庫,一個表,插入並從中檢索。將表添加到現有的數據庫IOS sqlite
但是,從屏幕2,當我試圖在同一個數據庫中創建一個表並插入值時,我無法。
這是我正在使用的代碼。
-(void) createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
_databasePath = [[NSString alloc]
initWithString: [docsDir stringByAppendingPathComponent:
@"coning.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: _databasePath ] == NO)
{
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS order (ID INTEGER PRIMARY KEY AUTOINCREMENT , NAME TEXT UNIQUE , ADDRESS TEXT UNIQUE, PHONE TEXT UNIQUE)";
if (sqlite3_exec(_contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(@"Failed to create table");
}
sqlite3_close(_contactDB);
} else {
NSLog(@"Failed to open/create database");
}
}
}
- (void)saveData {
sqlite3_stmt *statement;
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &_contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
@"INSERT OR REPLACE INTO order (name, address, phone) VALUES (\"%@\", \"%@\", \"%@\")",
@"name", @"address", @"phone"];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(_contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(@"added");
} else {
NSLog(@"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(_contactDB);
}
}
我一直使用相同的代碼,以表1中添加條目,但是當我做同樣的創建表2,它說「無法添加聯繫人」。有人可以建議我可能會出錯嗎?
我也想使表1的PK的FK表2
檢查ERRORMSG:http://www.sqlite.org/c3ref/errcode.html – bryanmac
檢查ERRORMSG ^^^和使用FMDB https://github.com/ccgus/fmdb – Eugene
什麼錯誤發生後調用'sqlite3_errmsg()'的消息? –