iPhone Dev iPhone Dev - 3 years ago 113
iOS Question

table creation fail in xcode for iPhone using sqlite

I used the following code for database creation in Xcode. It runs smoothly up to the

NSFilemanager
code, but after that it will terminating to
else
code that says
status.text=@"failed to open/create database";
so table can't be created.
I imported
sqlite3.h
and create
sqlDatabase
reference variable
sqlite3
still it doesn't work.

-(void)databaseCreate
{
NSString *docsDir;
NSString *dbPath;
NSArray *dirPath;

dirPath=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSLog(@"dirpath::%@",dirPath);

docsDir=[dirPath objectAtIndex:0];
NSLog(@"document directory::%@",docsDir);
dbPath=[[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"timerpro1.db"]];

NSLog(@"database path::%@",dbPath);
NSFileManager *fileManager=[NSFileManager defaultManager];

if([fileManager fileExistsAtPath: dbPath] == NO)
{
const char *databsPath=[dbPath UTF8String];
NSLog(@"treat filemanager");


if(sqlite3_open(databsPath,&sqlDatabase) == SQLITE_OK)
{
char *err;
NSLog(@"create inside");
const char *sql_stmt="CREATE TABLE IF NOT EXISTS PRJDATA(ID INTEGER PRIMERY KEY AUTOINCREMENT,PRJ_NAME TEXT,PRJ_DATE TEXT,TIME_POINT1 TEXT,TIME_POINT2 TEXT,TIME_POINT3 TEXT,POINT2_DIFF_MIN TEXT,POINT2_DIFF_SEC TEXT,POINT3_DIFF_MIN TEXT,POINT3_DIFF_SEC TEXT)";

if (sqlite3_exec(sqlDatabase, sql_stmt, NULL, NULL, &err)!=SQLITE_OK)
{
status.text=@"failed to create table";
}
sqlite3_close(sqlDatabase);
}
else
{
status.text=@"failed to open/create database";
}
}
[fileManager release];
}

Rob Rob
Answer Source

The immediate problem is that you have to replace the reference to NSDocumentationDirectory with NSDocumentDirectory.

Two asides:

  1. When you get failures, you should examine sqlite3_errmsg(), as you'll often get descriptive errors. For example, your sqlite3_exec() statement will fail, even after you fix the NSDocumentDirectory mistake.

    If you look at the sqlite3_errmsg() error message, it will tell you that you have an error near the AUTOINCREMENT clause. If you look at the SQL carefully, you'll notice that you have misspelled PRIMARY KEY. That would be more difficult to find in the absence of the sqlite3_errmsg(), which brings our attention to the particular portion of the SQL.

  2. You can simplify dbPath declaration:

    dbPath=[docsDir stringByAppendingPathComponent:@"timerpro1.db"];`
    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download