【问题标题】:create sqlite db programmatically in iphone sdk在 iphone sdk 中以编程方式创建 sqlite db
【发布时间】:2011-04-05 16:40:18
【问题描述】:

我正在尝试在运行时以编程方式创建一个 sqlite 数据库。任何人都可以说如何在 iphone sdk 中创建它。

【问题讨论】:

    标签: iphone database sqlite


    【解决方案1】:

    只需调用 sqlite3_open 函数,如果路径上不存在数据库,它将创建一个数据库。

    // generate databasePath programmatically
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) 
    {
    
    // your  code here
    }
    

    如果您需要更多代码示例,请发表评论

    【讨论】:

    • 有关此主题的任何教程,saurabh。请你给我们谢谢你
    【解决方案2】:
    -(void)viewDidLoad
    {
        [super viewDidLoad];
        NSString *docsDir;
        NSArray *dirPaths;
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
        docsDir = [dirPaths objectAtIndex:0];
    
        // Build the path to the database file
        databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.sqlite"]];
        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 CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
    
                if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
                {
                    NSLog(@"if");
    
                }
    
                sqlite3_close(contactDB);
    
            } else 
            {
                NSLog(@"else");
    
            }
        }
        [filemgr release];
    
    }
    
    -(IBAction)table
    {
        NSString *docsDir;
        NSArray *dirPaths;
    
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
        docsDir = [dirPaths objectAtIndex:0];
    
        // Build the path to the database file
        databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.sqlite"]];
    
        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 LIST (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)";
    
                if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
                {
    
                      NSLog(@"tables failed");
                   // status.text = @"Failed to create table";
                }
    
                sqlite3_close(contactDB);
    
            }
            else 
            {
    
                NSLog(@"tables failed");
                //status.text = @"Failed to open/create database";
    
            }
        }
    
        [filemgr release];
    }  
    

    【讨论】:

    • 导入.m文件#import并在你的项目libsqlite3.0.dylib中添加框架......谢谢:)
    【解决方案3】:

    导入.m文件#import sqlite3.h并在你的项目libsqlite3.0.dylib中添加框架

    首先创建 NSObject 类并将其命名为 Database。 在 .h 类中

      @interface database : NSObject
    
       {
        NSString *databasePath;
    NSString *databaseName;
    sqlite3 *myDatabase;
    NSArray *documentPaths;
    NSString *documentsDir;  
    
    }
    

    //---初始方法-------

     -(void)createDatabaseIfNeeded;
    

    //-----------------路径查找方法---------------------//

      -(void)pathFind;
    

    //-----------------写入值----------------------//

      -(void)writeValueInSettings:(NSMutableArray *)arrayvalue;
    

    //--------------------从设置表中取值------------//

        -(NSMutableArray *)fetchValue;
    

    //--------------------更新值------------------------//

        -(void)updateSetting:(NSArray *)arr;
    

    .m 类写

     -(id)init
      {
    if((self=[super init]))
    {
        [self createDatabaseIfNeeded];
    }
    return self;    
      }
    
     //-----------create database if needed method--------------//
     -(void)createDatabaseIfNeeded
      {
    [self pathFind];
    
    BOOL success;
    NSFileManager *filemgr = [NSFileManager defaultManager];
    success=[filemgr fileExistsAtPath:databasePath];
    
    if (success)return;
    
    NSLog(@"not success");
    
    //Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath]  stringByAppendingPathComponent:databaseName];
    // Copy the database from the package to the users filesystem
    [filemgr copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    
    
        }
    

    //----------------路径查找-----------------//

      -(void)pathFind
        {
    databaseName = @"accDataBase.DB";
    // Get the path to the documents directory and append the databaseName
    documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
      }
    

    //-----------------在设置中写入值----------------//

      -(void)writeValueInSettings:(NSMutableArray *)arrayvalue
       {   
       NSLog(@"%@",arrayvalue);
    
       if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
    
      {
        database *objectDatabase=[[database alloc]init];
    
        NSString *stringvalue2=[objectDatabase countValue];
        [objectDatabase release];
        int intvalue1=[stringvalue2 intValue];
    
        intvalue1=intvalue1+1;
        NSLog(@"opened");
        NSString *sql1;
    
        sql1=[[NSString alloc] initWithFormat:@"insert into setting values('%i','%i','%i','%@','%i','%i','%@','%i','%i','%i','%i','%i','%i','%@');",intvalue1,
              [[arrayvalue objectAtIndex:0] intValue],[[arrayvalue objectAtIndex:1] intValue],[arrayvalue objectAtIndex:2],[[arrayvalue objectAtIndex:3] intValue],[[arrayvalue objectAtIndex:4]intValue ],[arrayvalue objectAtIndex:5],[[arrayvalue objectAtIndex:6]intValue],[[arrayvalue objectAtIndex:7]intValue ],[[arrayvalue objectAtIndex:8] intValue],[[arrayvalue objectAtIndex:9] intValue],[[arrayvalue objectAtIndex:10]intValue ],[[arrayvalue objectAtIndex:11]intValue],[arrayvalue objectAtIndex:12]];
        char *err1;
        if (sqlite3_exec(myDatabase,[sql1 UTF8String],NULL,NULL,&err1)==SQLITE_OK)
        {
            NSLog(@"value inserted:");
        }
        [sql1 release];
        sqlite3_close(myDatabase);
    }
    

    } //------------获取所有值-------------//

       -(NSMutableArray *)fetchValue
        {
    NSMutableArray *list=nil;
    
        list=[[[NSMutableArray alloc]init] autorelease];
    
    if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
    {
    
        NSString *sql=[NSString stringWithFormat: @"select * from setting where primaryKey=1"];
              sqlite3_stmt *statement;
    
        if(sqlite3_prepare_v2(myDatabase, [sql UTF8String], -1,&statement, NULL)==SQLITE_OK)
        {
            if(sqlite3_step(statement)==SQLITE_ROW)
            {
                for(int i=0;i<=13;i++)
                {
                    char *pass=(char*)sqlite3_column_text(statement,i);
                    NSString *msg=[[NSString alloc]initWithUTF8String:pass];
                    [list addObject:msg];
                    [msg release];
                }
    
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(myDatabase);
       }
    
      return list;
    
          }
    

    //----更新设置表方法---------------//

        -(void)updateSetting:(NSArray *)arr
        {    
    if(sqlite3_open([databasePath UTF8String],&myDatabase)==SQLITE_OK)
    {
        NSLog(@"opened");
        sqlite3_stmt *compiledStmt;
    
       // NSLog(@"%@",arr);
    
        NSString *sqlStmt=[NSString stringWithFormat:@"UPDATE setting SET ragular=%i,cycle=%i, flow='%@', hour=%i,minute=%i,formate='%@' ,tenminute=%i ,thirtyminute=%i,sixtymin=%i, twentymin=%i, fourtyfivemin=%i ,other='%@',formatemessage ='%@' WHERE primaryKey=%i;",[[arr objectAtIndex:0]intValue],[[arr objectAtIndex:1]intValue],[arr objectAtIndex:2],[[arr objectAtIndex:3]intValue],[[arr objectAtIndex:4]intValue],[arr objectAtIndex:5],[[arr objectAtIndex:6]intValue],[[arr objectAtIndex:7]intValue],[[arr objectAtIndex:8]intValue],[[arr objectAtIndex:9]intValue],[[arr objectAtIndex:10]intValue],[arr objectAtIndex:11],[arr objectAtIndex:12],1];
     //   NSLog(@"%@",sqlStmt);
         if(sqlite3_prepare_v2(myDatabase, [sqlStmt UTF8String],-1,&compiledStmt, NULL)==SQLITE_OK) 
          {
        NSLog(@"updateding......cycle");
            }
        sqlite3_step(compiledStmt);
        sqlite3_close(myDatabase);
    }
    
      }
    

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      相关资源
      最近更新 更多