2012-05-11 17 views
8

Sono nuovo nello sviluppo di iPhone. Ho creato il database usando il terminale in mac os x. Ora sto cercando di creare il database in modo programmatico nell'applicazione iPhone usando objective- C. Qualcuno può dirmi un buon sito in cui posso visualizzare le applicazioni di esempio che funzionano e c'è qualche sito per imparare il tutorial? Per favore qualcuno mi aiuti.Come creare database SQLite a livello di codice?

+2

vi suggerisco di cercare in google. Stack overflow non dovrebbe il tuo motore di ricerca. Dato che sei nuovo nello stack overflow, quindi non ho segnato il down-vote. – Nit

+0

Leggete [Domande frequenti] (http://stackoverflow.com/faq) prima –

risposta

13

Da a tutorial on Techtopia:

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.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 CONTACTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, ADDRESS TEXT, PHONE TEXT)"; 

     if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) { 
      status.text = @"Failed to create table"; 
     } 
     sqlite3_close(contactDB); 
    } 
    else { 
     status.text = @"Failed to open/create database"; 
    } 
} 
[filemgr release]; 
+2

'dbpath == databasePath'? 'contactDB' ha dichiarato dove? – wcochran

0

Se si vuole essere utilizzando il database di dati Persistenza esaminare CoreData è una buona risorsa per la memorizzazione di grandi quantità di dati per un app, tenere a mente, però CoreData è non Database.

È possibile utilizzare SQLite abbastanza facilmente su una piattaforma iOS, ma non si è fornito con gli strumenti visivi per svilupparlo come si fa con CoreData

Se si memorizzano piccole quantità di dati guardare direttamente la memorizzazione delle informazioni in plists .

Se si archiviano alcune stringhe, interi o bool si dovrebbe usare NSUserDefaults

Senza ulteriori informazioni non ho potuto dire con certezza quale sarebbe il metodo migliore per voi

Altre risorse:

  1. CoreData Tutorial
  2. Data Management
1

Creare una base dati per la tua app per iPhone è un po 'lungo ma ha molti passaggi ma è così semplice:

Prima di tutto dovresti scaricare mozilla fire fox e scaricare i suoi add-on e puoi trovare sqlite opzione del database facendo clic su Opzioni Strumenti. E puoi creare un nuovo file Databse con colonne e righe. Il suo semplice processo per creare un file di base dati e dopo che è possibile includere quel file nel progetto del codice X.

Ad esempio: - proprio come un'immagine comunemente inclusa nel progetto Xcode.

dopo che scrivere il seguente codice si sta lavorando bello per me :)

Nella tua.file di m scrivere il seguente codice SQLite

#import "YourHeaderFile" 

static sqlite3 *database = nil; 
static sqlite3_stmt *addStmt = nil; 
static sqlite3_stmt *updateStmt = nil; 


@implementation 'YourImplementClass' 



- (NSString *) getDBPath { 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    return [documentsDir stringByAppendingPathComponent:@"YourDataBaseFileName.sqlite"]; 
} 

- (void) insertValueToDatabase { 

    NSString *dbPath =[self getDBPath]; 

    NSString *select_Meal = dummy_select_Meal; 
    NSString *dateTime = dummy_date_Time; 
    NSString *location = dummy_location; 
    NSString *mealItem = dummy_mealItem; 

    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) { 

     const char *sqlDB = "Insert into iHad(Mealtype,DateAndTime,Location,Mealitem) VALUES (?,?,?,?)"; 

     if(sqlite3_prepare_v2(database, sqlDB, -1, &addStmt, NULL) != SQLITE_OK) 
      NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database)); 

     sqlite3_bind_text(addStmt, 1, [select_Meal UTF8String], -1, SQLITE_TRANSIENT); 
     sqlite3_bind_text(addStmt, 2, [dateTime UTF8String], -1, SQLITE_TRANSIENT); 
     sqlite3_bind_text(addStmt, 3, [location UTF8String], -1, SQLITE_TRANSIENT); 
     sqlite3_bind_text(addStmt, 4, [mealItem UTF8String], -1, SQLITE_TRANSIENT); 

     if(SQLITE_DONE != sqlite3_step(addStmt)) 
      NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database)); 
     //else 
      //SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid 
      //coffeeID = sqlite3_last_insert_rowid(database); 

     //Reset the add statement. 
     sqlite3_reset(addStmt); 

    } 
    else 
     sqlite3_close(database); 

} 

e per risparmiare può creat un metodo come questo

-(void)saveButtonClick 
{ 

    if (![dummy_select_Meal length] || ![dummy_mealItem length]) 
    { 
     UIAlertView *alert = [[UIAlertView alloc] init]; 
     [alert setTitle:@"Select Meal Type/Meal Item"]; 
     [alert setDelegate:self]; 
     [alert addButtonWithTitle:@"Ok"]; 
     [alert show]; 
     [alert release]; 
    } 

    else 
    { 
     indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(30,30,50,50)]; 
     indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;//UIActivityIndicatorViewStyleWhiteLarge;// 

     [self insertValueToDatabase];-----------------------> To insert data into data base 

     iHadAppDelegate *delegate = [[UIApplication sharedApplication]delegate]; 
     [delegate readMealsFromDatabase]; 

     [rootController reloadTable_SaveButton]; 

    } 
    [rootController showTablePopupAction:nil]; 

} 

Ancora se avete qualche problema poi mi risponderà farò aiuto voi :)

3
#pragma mark - SQLite 

-(void)createDatabase 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    databasePath = [[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"timings.db"]]; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:databasePath] == FALSE) 
    { 
     if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK) 
     { 
      const char *sqlStatement = "CREATE TABLE IF NOT EXISTS TIMINGS (ID INTEGER PRIMARY KEY AUTOINCREMENT, TIMESTAMP TEXT, TIMING TEXT)"; 
      char *error; 
      sqlite3_exec(timingsDatabase, sqlStatement, NULL, NULL, &error); 
      sqlite3_close(timingsDatabase); 
     } 
    } 
} 

-(void)storeTiming 
{ 
    if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK) 
    { 
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
     [dateFormatter setDateFormat:@"HH:mm:ss.SSS"]; 

     NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO TIMINGS (TIMESTAMP, TIMING) VALUES (\"%@\", \"%@\")", [dateFormatter stringFromDate:startDate], stopWatchLabel.text]; 

     char *error; 
     sqlite3_exec(timingsDatabase, [insertStatement UTF8String], NULL, NULL, &error); 
     sqlite3_close(timingsDatabase); 

     [dateFormatter release]; 
    } 
} 

-(void)getTimings 
{ 
    if (sqlite3_open([databasePath UTF8String], &timingsDatabase) == SQLITE_OK) 
    { 
     NSString *queryStatement = [NSString stringWithFormat:@"SELECT TIMESTAMP, TIMING FROM TIMINGS"]; 

     sqlite3_stmt *statement; 
     if (sqlite3_prepare_v2(timingsDatabase, [queryStatement UTF8String], -1, &statement, NULL) == SQLITE_OK) 
     { 
      while (sqlite3_step(statement) == SQLITE_ROW) { 
       NSLog(@"Timestamp: %s Timing: %s", sqlite3_column_text(statement, 0), sqlite3_column_text(statement, 1)); 
      } 
      sqlite3_finalize(statement); 
      sqlite3_close(timingsDatabase); 
     } 
    } 
} 

controllare questi esempi:

  1. http://www.techotopia.com/index.php/An_Example_SQLite_based_iOS_4_iPhone_Application
  2. http://www.icodeblog.com/2008/09/22/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-4/
0

chiamare questa funzione in didFinishLaunchingWithOptions:

-(void)createdb 
    { 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES); 
     NSString *documentsDirectory = [paths objectAtIndex:0]; 
     NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:@"emp.sqlite"]; 

     NSURL *dbURL = [NSURL fileURLWithPath:dbPath]; 

     // copy a database from the bundle if not present 
     // on disk 
     NSFileManager *fm = [NSFileManager defaultManager]; 
     if (![fm fileExistsAtPath:dbPath]) 
     { 
      NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"emp" withExtension:@"sqlite"]; 
      NSError *error = nil; 
      if (!bundlePath || ![fm copyItemAtURL:bundlePath toURL:dbURL error:&error])       
      { 
       NSLog(@"error copying database from bundle: %@", error); 
      } 
     } 
     else 
     { 
      NSLog(@"Success in Copy file"); 
     } 
    } 

Click here to Download Full Example

2

Creare database SQLite in Xcode

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    // Override point for customization after application launch. 

    [self createDb]; 

    return YES; 
} 


-(void)createDb 
{ 
    NSArray *dir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    NSString *dbPath=[NSString stringWithFormat:@"%@/userDb.sqlite",[dir lastObject]]; 

    sqlite3 *db; 

    NSFileManager *fm=[NSFileManager new]; 

    if([fm fileExistsAtPath:dbPath isDirectory:nil]) 
    { 
     NSLog(@"Database already exists.."); 
     return; 
    } 

    if (sqlite3_open([dbPath UTF8String],&db)==SQLITE_OK) 
    { 
     const char *query="create table user (userName VARCHAR(20),userAdd VARCHAR(20), userPass VARCHAR(20))"; 

     if (sqlite3_exec(db, query, NULL, NULL, NULL)==SQLITE_OK) 
     { 
      NSLog(@"User table created successfully.."); 
     }else 
     { 
      NSLog(@"User table creation failed.."); 
     } 

    }else 
    { 
     NSLog(@"Open table failed.."); 
    } 
    sqlite3_close(db); 

} 
0

chiamare questa funzione di poppa er avviso memmory.

- (IBAction) SaveData: (UIButton *) {mittente

sqlite3_stmt *statement; 
const char *dbPath = [databasePath UTF8String]; 

if(sqlite3_open(dbPath, &contactDB)== SQLITE_OK){ 

    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO CONTACTS(NAME,ADDRESS,PHONE)VALUES(\"%@\",\"%@\",\"%@\")",_name.text,_address.text,_phoneNo.text]; 

    const char *insert_stmt = [insertSQL UTF8String]; 
    sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL); 
    if (sqlite3_step(statement)== SQLITE_DONE) { 
     _status.text = @"Contact added"; 
     _name.text = @""; 
     _address.text = @""; 
     _phoneNo.text = @""; 
    }else{ 
     _status.text = @"Failed to add contact"; 
    } 
    sqlite3_finalize(statement); 
    sqlite3_close(contactDB); 

} 

}

Problemi correlati