我正在处理从一个viewcontroller到另一个viewcontroller的sqlite数据库的通信,但是我在第二个视图控制器上没有得到数据库。贝娄是我用它的代码。: -
在First View控制器上
//Creating a table of MOtivational Thoughts
dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPath objectAtIndex:0];
Second.databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"S.H.E.D_DB"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([ filemgr fileExistsAtPath: Second.databasePath] == NO) {
const char *dbpath = [Second.databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS THOUGHTS (ID integer ,Motivation_Thaought TEXT)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(@"Failed to create table");
}
else
{
NSLog(@" created table");
}
sqlite3_close(contactDB);
} else {
}
}
// Fetching Data from table of MOtivational Thoughts
if(sqlite3_open([Second.databasePath UTF8String], &contactDB) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
int randomNumber = [self getRandomNumberBetween:0 to:6];
NSString *queryString = [NSString stringWithFormat:@"Select * FROM THOUGHTS where ID= '%d'",randomNumber];
const char* sql = [queryString UTF8String];
NSLog(@"path value : %@", Second.databasePath);
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(contactDB, sql, -1, &compiledStatement, nil)==SQLITE_OK) {
// Loop through the results and add them to the feeds array
NSLog(@"Ready to enter while loop");
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSLog(@"reading");
NSString *aid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
motivationView.text = aid;
NSLog(@"Thought of the day %@", aid);
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(contactDB);
// Do any additional setup after loading the view from its nib.
}
在第二个视图控制器上
NSLog(@"path value : %@", databasePath);
if(sqlite3_open([databasePath UTF8String], &contactDB) == SQLITE_OK){
char *errMsg;
const char *sql_stmt =
"CREATE TABLE IF NOT EXISTS SHEDSLIST (SHED_ID integer ,SHED_Name TEXT ,SHED_Description TEXT, SHED_TIME DATETIME)";
if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
NSLog(@"Failed to create table");
}
else
{
NSLog(@" created table");
}
sqlite3_close(contactDB);
} else {
}
请找出我的错误并给我提供可靠的解决方案。
答案 0 :(得分:0)
您可能应该在SecondViewController中以self.databasePath
访问数据库路径,因为我相信您已为此创建了一个属性。而不是你试图访问一些实例变量databasePath
。在FirstViewController中查看以下代码:
Second.databasePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"S.H.E.D_DB"]];