2016-06-16 3 views
0

Я создал несколько таблиц в моей базе данных. И теперь я хочу вставить данные в эти таблицы. Как вставить несколько табличных данных может кто-нибудь помочь в этом.Вставка нескольких таблиц данных в базу данных sqlite

Я написал этот код для создания 1 таблицы:

NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO ATRG (id, name, language,imgurl) VALUES (\"%@\",\"%@\",\"%@\",\"%@\")", ID, name, lang,imgUrl]; 
const char *insert_stmt = [insertSQL UTF8String]; sqlite3_prepare_v2(_globalDataBase, insert_stmt, -1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_DONE) 
{ 
NSLog(@"Record Inserted"); 

} else { NSLog(@"Failed to Insert Record"); 
} 
+0

вставки данных в нескольких таблицах, которые вы в вашем коде многократный запрос. –

+0

Как написать этот запрос? для одной таблицы –

+0

Вставить в таблицу1 (имя) значение ('abc') Вставить в таблицу2 (имя) значение ('abc') –

ответ

1

Попробуйте это, я надеюсь, что это будет полезно !! Это мой код для данных вставки

#import "Sqlitedatabase.h" 
@implementation Sqlitedatabase 
+(NSString*)getDatabasePath 
{ 
    NSString *docsDir; 
    NSArray *dirPaths; 
    sqlite3 *DB; 
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    docsDir = dirPaths[0]; 

    NSString *databasePath = [docsDir stringByAppendingPathComponent:@"myUser.db"]; 

    NSFileManager *filemgr = [[NSFileManager alloc]init]; 

    if ([filemgr fileExistsAtPath:databasePath]==NO) { 

     const char *dbpath = [databasePath UTF8String]; 
     if (sqlite3_open(dbpath,&DB)==SQLITE_OK) { 

      char *errorMessage; 
      const char *sql_statement = "CREATE TABLE IF NOT EXISTS users(ID INTEGER PRIMARY KEY AUTOINCREMENT,FIRSTNAME TEXT,LASTNAME TEXT,EMAILID TEXT,PASSWORD TEXT,BIRTHDATE DATE)"; 
      if (sqlite3_exec(DB,sql_statement,NULL,NULL,&errorMessage)!=SQLITE_OK) { 

       NSLog(@"Failed to create the table"); 
      } 
      sqlite3_close(DB); 
     } 
     else{ 
      NSLog(@"Failded to open/create the table"); 
     } 
    } 
    NSLog(@"database path=%@",databasePath); 
    return databasePath; 
} 

+(NSString*)encodedString:(const unsigned char *)ch 
{ 
    NSString *retStr; 
    if(ch == nil) 
     retStr = @""; 
    else 
     retStr = [NSString stringWithCString:(char*)ch encoding:NSUTF8StringEncoding]; 
    return retStr; 
} 
+(BOOL)executeScalarQuery:(NSString*)str{ 

    NSLog(@"executeScalarQuery is called =%@",str); 

    sqlite3_stmt *statement= nil; 
    sqlite3 *database; 
    BOOL fRet = NO; 
    NSString *strPath = [self getDatabasePath]; 
    if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) { 
     if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) { 
      if (sqlite3_step(statement) == SQLITE_DONE) 
       fRet =YES; 
     } 

     sqlite3_finalize(statement); 
    } 
    sqlite3_close(database); 
    return fRet; 
} 

+(NSMutableArray *)executeQuery:(NSString*)str{ 

sqlite3_stmt *statement= nil; // fetch data from table 
sqlite3 *database; 
NSString *strPath = [self getDatabasePath]; 
NSMutableArray *allDataArray = [[NSMutableArray alloc] init]; 
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) { 
    if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) { 


     while (sqlite3_step(statement) == SQLITE_ROW) { 
      NSInteger i = 0; 
      NSInteger iColumnCount = sqlite3_column_count(statement); 
      NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
      while (i< iColumnCount) { 
       NSString *str = [self encodedString:(const unsigned char*)sqlite3_column_text(statement, (int)i)]; 


       NSString *strFieldName = [self encodedString:(const unsigned char*)sqlite3_column_name(statement, (int)i)]; 

       [dict setObject:str forKey:strFieldName]; 
       i++; 
      } 

      [allDataArray addObject:dict]; 
     } 
    } 

    sqlite3_finalize(statement); 
} 
sqlite3_close(database); 
return allDataArray; 
} 
@end 

И назвал этот метод, где вы хотите использовать !!

NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO users(firstname,lastname,emailid,password,birthdate) VALUES ('%@','%@','%@','%@','%@')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text]; 
if ([Sqlitedatabase executeScalarQuery:insertSql]==YES) 
{ 

    [self showUIalertWithMessage:@"Registration succesfully created"]; 

}else{ 
    NSLog(@"Data not inserted successfully"); 
} 

И если вы хотите получать данные из таблицы, то вы можете это сделать!

NSString *insertSql = [NSString stringWithFormat:@"select emailid,password from users where emailid ='%@' and password = '%@'",[_usernameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]],[_passwordTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]]; 

     NSMutableArray *data =[Sqlitedatabase executeQuery:insertSql]; 
     NSLog(@"Fetch data from database is=%@",data); 

Несколько запросов на выполнение !!

NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO users (firstname,lastname,emailid,password,birthdate) VALUES ('%@','%@','%@','%@','%@')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text]; 

    NSString *insertSql1 = [NSString stringWithFormat:@"INSERT INTO contact (firstname,lastname,emailid,password,birthdate) VALUES ('%@','%@','%@','%@','%@')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text]; 

    NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:insertSql,insertSql1,nil]; 

    for (int i=0; i<array.count; i++) 
    { 
     [Sqlitedatabase executeScalarQuery:[array objectAtIndex:i]]; 
    } 
+0

Да за один раз вы можете вставлять данные в одну таблицу –

+0

Вы должны написать для отдельного запроса для нескольких таблиц –

+0

Напишите отдельный запрос запроса и добавьте в Nsarray и выполнить один за другим Запрос –

Смежные вопросы