Как создать пользовательский файл sqlite в ios?

Я работаю над приложением, где используется локальная база данных как sqlite.

Где я хочу создать пользовательский файл для sqlite, я не знаю, как это сделать.

Любая помощь будет оценена.

1 ответ

  1. Прежде всего добавьте файл ниже в свой проект.

    https://github.com/ConnorD/simple-sqlite

    Затем создайте базу данных.SQLite файл в проект. База данных содержит имя пользователя, фамилию и профиль picutre.

    И добавьте код ниже в файл AppDelegate.

    - (void)createEditableCopyOfDatabaseIfNeeded
    { 
        // First, test for existence. 
        BOOL success; 
        NSFileManager *fileManager = [NSFileManager defaultManager]; 
        NSError *error; 
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0]; 
        //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"testing" message:@"path for database" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        //    [alert show];
        //    [alert release];
    
        NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"Category_DB.sqlite"];
    
            //NSLog(@"Default  writableDBPath: %@",writableDBPath);
        success = [fileManager fileExistsAtPath:writableDBPath]; 
    
        if (success) return; 
        // The writable database does not exist, so copy the default to the appropriate location. 
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Category_DB.sqlite"];
    
        //NSLog(@"Default : %@",defaultDBPath);
        success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
       // NSLog(@"Success");
        if (!success) { 
            NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
        } 
    }
    

    Вызовите этот метод в свойdidFinishLaunchingWithOptions

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
    [self createEditableCopyOfDatabaseIfNeeded];
    return NO;
    }
    

    Теперь напишите ниже код в контроллер представления, где вы хотите использовать запросы.

    -(void)databaseOpen
    {
        NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [path objectAtIndex:0];
        NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:@"Category_DB.sqlite"];
        myDatabase = [[Sqlite alloc] init];
        [myDatabase open:myDBnew];
       // NSLog(@"database opened");
    
    }
    

    Для запроса select:

    [self databaseOpen];    
    NSString *query_fetch=[NSString stringWithFormat:@"select Max(session_id) from Report"];
    NSMutableArray *userData=[[myDatabase executeQuery:query_fetch]mutableCopy];
    

    Если вы хотите сохранить изображение в базу данных

    -(NSString *) getImagePath{
         /* *** Modify on 16 01 2012 by Prerak   *** */
    
         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
         NSString *documentsDirectory = [paths objectAtIndex:0];
    
         NSError *error;
         [[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:&error];
    
         return documentsDirectory;
    }
    

    Если вы хотите получить изображение в базу данных

    arrProfilepic = [[NSMutableArray alloc]init];
        NSError *error = nil;
        NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
        NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath: stringPath  error:&error];
    
        NSLog(@"File Path Array is %@",filePathsArray);
    
        for(int i=0;i<[filePathsArray count];i++)
        {
            NSString *strFilePath = [filePathsArray objectAtIndex:i];
            if ([[strFilePath pathExtension] isEqualToString:@"jpg"] || [[strFilePath pathExtension] isEqualToString:@"png"] || [[strFilePath pathExtension] isEqualToString:@"PNG"])
            {
                NSString *imagePath = [[stringPath stringByAppendingString:@"/"] stringByAppendingString:strFilePath];
                NSData *data = [NSData dataWithContentsOfFile:imagePath];
                //NSLog(@"Data %@", data);
                if(data)
                {
                    UIImage *image = [UIImage imageWithData:data];
                    NSLog(@"Image %@", image);
                    [arrProfilepic addObject:image];
                }
            }
    
        }
        NSLog(@"profile is %@",arrProfilepic);
    

    Для запроса Insert:

     NSString *documentsDirectory = [self getImagePath];//save image to database
      NSString *imagePath;
      imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"User_%d.png",newid]];
      NSString *relativePathImage1=nil;
      NSArray *relativeArray=[imagePath componentsSeparatedByString:@"/Documents"];
      UIImage *thumbImage;
      thumbImage = [VcAddUser.portraitImageView.image imageScaledToFitSize:CGSizeMake(90, 90)];
        NSData *thumbData = UIImageJPEGRepresentation(thumbImage, 1.0f);
                  [thumbData writeToFile:imagePath atomically:YES];
    
    
    
    
     NSString *query_insert=[NSString stringWithFormat:@"Insert into UserDetails(User_id,User_fname,User_lname,User_image) values(%d,'%@','Smith','%@')",newid,VcAddUser.txtFUsername.text,relativePathImage1];
     NSMutableArray *userData=[[NSMutableArray alloc]init];
     userData=[[myDatabase executeQuery:query_insert];
     [database close];
    

    Для удаления запроса:

      NSString *query_user=[NSString stringWithFormat:@" delete from UserDetails where User_id=%d",Userid];
            [myDatabase executeNonQuery:query_user];
            [myDatabase close];
    
    
    **For Update query:**
    
    NSString *updatequery=[NSString stringWithFormat:@"Update UserDetails set User_fname='%@',User_lname='%@', User_image='%@' where User_id=%d",txtFUsername.text,txtLUsername.text,relativePathImage1,UseridUpdate];
        [myDatabase executeNonQuery:updatequery];
       // NSLog(@"Query user is %@",updatequery);
        [myDatabase close];
    

    Для Веб-Сервисов

    -(void) CallWebservice
    {
          NSMutableData  *responseData = [NSMutableData data];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:[NSURL URLWithString:@"give your web service url"]];
            [request setHTTPMethod:@"POST"];
            [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
            [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            [request setHTTPBody:[requestString dataUsingEncoding:NSUTF8StringEncoding]];
          NSURLConnection  *PostConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    }
    
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        [responseData setLength:0];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        [responseData appendData:data];
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
    {
       [self removeProgressIndicator];
        UIAlertView *alt=[[UIAlertView alloc]initWithTitle:@"Internet connection is not Available!" message:@"Check your network connectivity" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alt show];
    
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
       // check for response only
    
        /*NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    
        NSLog(@"%@",responseString);*/
    
        NSError *error;
        NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    
        NSLog(@"%@",results);
    }