我是iOS开发的新手。我正在尝试做一个简单的待办事项列表应用程序。我正在使用xocde 8和Objective-C语言。我尝试了几个教程,但无法创建数据库表。这是我的代码。
-(void)createOrOpenDB{
printf("createOrOpenDB: into this function \n");
NSArray *docsDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dirPaths = [docsDir objectAtIndex:0];
dbPathString = [[NSString alloc] initWithString: [dirPaths stringByAppendingPathComponent:@"person.db"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
char *err;
printf("createOrOpenDB: into this function before if statement \n");
if(![fileManager fileExistsAtPath:dbPathString]){
const char *dbPath = [dbPathString UTF8String];
printf("createOrOpenDB: into this functions 1st if statement \n");
//create db here
if(sqlite3_open(dbPath, &personDB) ==SQLITE_OK){
const char *sql_stnt = "CREATE TABLE IF NOT EXISTS PERSONS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER)";
if(sqlite3_exec(personDB, sql_stnt, NULL, NULL, &err) !=SQLITE_OK){
printf("Failed to create table\n");
}
sqlite3_close(personDB);
printf("createOrOpenDB: database table created\n");
}
}
}
当我按下添加按钮时,它没有给我任何错误。但它没有添加任何数据。 NSLog不在xcode 8中工作。所以我做了printf而不是。我的代码在if语句之前中断。谁能告诉我我做错了什么?
答案 0 :(得分:0)
这样做,
@Html.TextBoxFor(model => model.PlayerId, htmlAttributes: new { @readonly = "read-only", @class = "control-label col-md-2", Value = @Html.Raw(TempData["PlayerID"]) })
对于在此表中保存数据,
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
-(BOOL)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: @"student.db"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == YES)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "create table if not exists studentsDetail (regno integer primary key, name text, department text, year text)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(@"Failed to create table");
}
else
{
NSLog(@"Table Created Successfully");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(@"Failed to open/create database");
}
sqlite3_finalize(statement);
}
return isSuccess;
// NSLog(@"database %@", isSuccess);
}
每当表不存在时,它将创建表。
希望对你有帮助。