Deepak Pillai
Deepak Pillai

Reputation: 105

How can i insert encrypted data to sqlite. i'm getting an error while inserting encrypted data

How can i insert encrypted data to sqlite. i'm getting an error while inserting encrypted data. bcos the encrypted so many single quotes and double quotes so while am creating my sql the string is breaking. is there any other way to insert data without data lose. also i'm afraid to use add slashes method bsoc it may alter my actual encrypted data. Can anyone give me a suggestion.. Also please find my insert query function below

-(BOOL) insertItemData:(NSString *)encryptedData folderId:(NSString *)folderId
{
   bool giveBackValue = 0;

   database = [[[DBConnection alloc] init] autorelease];

  if(sqlite3_open([[database filePath] UTF8String], &db) == SQLITE_OK)
  {
    NSString *sql = [[[NSString alloc] initWithFormat:@"INSERT INTO tbl_content (FolderId, Content) VALUES ('%@', '%@');", folderId, encryptedData] autorelease];
    NSLog(@"%@",sql);
    char *sqlError;
    if(sqlite3_exec(db, [sql UTF8String], nil, nil, &sqlError) == SQLITE_OK)
    {
        giveBackValue = 1;
    }
    else
    {
        //Query exec failed

    }
}
else
{
    //DB Open failed
}

return giveBackValue;
}

My select query function

-(void)getFirstJsonListInFolder:(NSString *)folderId listCarrier:(NSMutableArray **)listCarrier
{
    database = [[[DBConnection alloc] init] autorelease];
    NSMutableArray *dummyListCarrier = [[[NSMutableArray alloc] init] autorelease];

    if (sqlite3_open([[database filePath] UTF8String], &db) ==SQLITE_OK)
    {
        NSString *sql = [[NSString alloc] initWithFormat:@"SELECT Content from tbl_content WHERE FolderId = '%@'", folderId];

    sqlite3_stmt *result;
    if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &result, nil) == SQLITE_OK)
    {
        while (sqlite3_step(result) == SQLITE_ROW)
        {
            char *contentList = (char *)sqlite3_column_text(result, 0);
            NSString *contentListString = [[NSString alloc] initWithUTF8String:contentList];
            [dummyListCarrier addObject:contentListString];
            [contentListString release];
        }
    }
    else 
    {
        //Query exec failed
    }
}
else
{
    //DB Open failed
}
*listCarrier = dummyListCarrier;
}

Upvotes: 0

Views: 622

Answers (1)

DivineDesert
DivineDesert

Reputation: 6954

You should avoid directly assigning values to the columns in sql statements. Instead you should use prepared statement and bind values to it.

NSString *sql = @"INSERT INTO tbl_content (FolderId, Content) VALUES ('?', '?');";
char *sql = (char *) [sql UTF8String];
sqlite3_bind_text(stmt, 1, [Content UTF8String], -1, SQLITE_TRANSIENT);

*This is not complete code

Upvotes: 1

Related Questions