How to store image in sqlite database in iphone? [closed] - iphone

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"image.sqlite"];
if (sqlite3_open_v2([path UTF8String], &database, SQLITE_OPEN_READWRITE, NULL) == SQLITE_OK)
{
if(selectStmt == nil)
{
const char *sql = "insert into imagetb(imagename,image) Values(?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &selectStmt, NULL) != SQLITE_OK)
// NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
NSLog(#"%s",sqlite3_errmsg(database));
}
sqlite3_bind_text(selectStmt, 1, [#"test.png" UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(selectStmt, 2, [data1 bytes], [data1 length], SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(selectStmt))
NSLog(#"get: %s",sqlite3_errmsg(database));
else
NSLog(#"scan data added");
}
//showimage
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
const char *sql = "select * from imagetb";// LIMIT 0,100 ";// where status = 1 ";
sqlite3_stmt *selectstatment;
if (sqlite3_prepare_v2(database, sql, -1, &selectstatment, NULL) == SQLITE_OK)
{
while (sqlite3_step(selectstatment) == SQLITE_ROW)
{
NSString *getorgstrid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstatment, 0)];
NSLog(#"id->%#",getorgstrid);
[getid addObject:getorgstrid];
NSString *getorgstrname = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstatment, 1)];
NSLog(#"name->%#",getorgstrname);
[getname addObject:getorgstrname];
NSData *getorgstrimage = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstatment,2)length:sqlite3_column_bytes(selectstatment, 2)];
[getimage addObject:getorgstrimage];
}
}
sqlite3_finalize(selectstatment);
}
//[tblorgland reloadData];
UIImage *image1 = [UIImage imageWithData:[getimage lastObject]];
NSLog(#"image%#",image1);
[getImageview setImage:image1];
[pool release];
==============================================================================
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"image.sqlite"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
getid=[[NSMutableArray alloc]init];
getname=[[NSMutableArray alloc]init];
getimage=[[NSMutableArray alloc]init];
[self downloadimage];
[self makeDBCopyAsNeeded];
}
-(void)downloadimage
{
NSLog(#"Downloading...");
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://0.tqn.com/d/graphicssoft/1/7/g/A/5/psptubezdotcom_003.png"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"%#",docDir);
NSLog(#"saving png");
pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
img=[[UIImage alloc]initWithData:data1];
[data1 writeToFile:pngFilePath atomically:YES];
NSLog(#"saving jpeg");
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/test.jpeg",docDir];
NSLog(#"jpegFilePath:%#",jpegFilePath);
data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(#"saving image done");
[image release];
}
- (void) makeDBCopyAsNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"image.sqlite"];
success = [fileManager fileExistsAtPath:writableDBPath];
NSString *dbPath = [self getDBPath];
NSLog(#"%#",dbPath);
if (success)
{
NSLog(#"Database Success Created");
return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"image.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success)
{
NSLog(#"Database:->%s",sqlite3_errmsg(database));
}
}

It is not recommended to store the image data in the sqlite. But if you want to store the image data then use this link
Save image data to sqlite database in iphone
Hope this will helps you..

You better use caches to store your images, and use database to store their names or some unique id's

Just write following code in -(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo: if you are getting image from gallery or Camera otherwise skip code under if (imageData != nil) and just use below code to save image in sqlite
NSData * imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(#"Image data length== %d",imageData.length);
if (imageData != nil)
{
UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)];
NSData * imageData = UIImageJPEGRepresentation(resizedImg, 0.2);
NSLog(#"*** Image data length after compression== %d",imageData.length);
NSString *nameofimg=[NSString stringWithFormat:#"%#",resizedImg];
NSString *substring=[nameofimg substringFromIndex:12];
NSString *new=[substring substringToIndex:7];// Get image name
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory=[path objectAtIndex:0];
NSString *newFilePath = [NSString stringWithFormat:[documentdirectory stringByAppendingPathComponent: #"/%#.png"],new];
[imageData writeToFile:newFilePath atomically:YES];
imgpath=[[NSString alloc]initWithString:newFilePath];
NSLog(#"doc img in img method === %#",imgpath);
}
databasepath=[app getDBPath]; // i have this method in delegate
if (sqlite3_open([databasepath UTF8String], &dbAssessor) == SQLITE_OK)
{
NSString *selectSql = [NSString stringWithFormat:#"insert into imagetb(imagename,image) VALUES(\"%#\",\"%#\") ;",yourImgName,imgpath];
NSLog(#"Query : %#",selectSql);
const char *sqlStatement = [selectSql UTF8String];
sqlite3_stmt *query_stmt;
sqlite3_prepare(dbAssessor, sqlStatement, -1, &query_stmt, NULL);
if(sqlite3_step(query_stmt)== SQLITE_DONE)
{
NSLog(#"home image updated. :)");
app.houseImage=imgpath;
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Sorry" message:#"Failed To Save Home Image." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
sqlite3_finalize(query_stmt);
}
sqlite3_close(dbAssessor);

Related

How to show image from documents directory to imageview?

I am using sqlite db to save image path of document directory. Here is my code:
NSData * imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(#"Image data length== %d",imageData.length);
if (imageData != nil)
{
UIImage *resizedImg = [self scaleImage:[UIImage imageWithData:imageData] toSize:CGSizeMake(150.0f,150.0f)];
NSData * imageData = UIImageJPEGRepresentation(resizedImg, 0.2);
NSLog(#"*** Image data length after compression== %d",imageData.length);
NSString *nameofimg=[NSString stringWithFormat:#"%#",resizedImg];
NSString *substring=[nameofimg substringFromIndex:12];
NSString *new=[substring substringToIndex:7];// Get image name
NSArray *path=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory=[path objectAtIndex:0];
NSString *newFilePath = [NSString stringWithFormat:[documentdirectory stringByAppendingPathComponent: #"/%#.png"],new];
[imageData writeToFile:newFilePath atomically:YES];
imgpath=[[NSString alloc]initWithString:newFilePath];
NSLog(#"doc img in img method === %#",imgpath);
}
databasepath=[app getDBPath]; // i have this method in delegate
if (sqlite3_open([databasepath UTF8String], &dbAssessor) == SQLITE_OK)
{
NSString *selectSql = [NSString stringWithFormat:#"insert into imagetb(imagename,image) VALUES(\"%#\",\"%#\") ;",yourImgName,imgpath];
NSLog(#"Query : %#",selectSql);
const char *sqlStatement = [selectSql UTF8String];
sqlite3_stmt *query_stmt;
sqlite3_prepare(dbAssessor, sqlStatement, -1, &query_stmt, NULL);
if(sqlite3_step(query_stmt)== SQLITE_DONE)
{
NSLog(#"home image updated. :)");
app.houseImage=imgpath;
}
else
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Sorry" message:#"Failed To Save Home Image." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
sqlite3_finalize(query_stmt);
}
sqlite3_close(dbAssessor);
These code save the image in document directory and path in sqlite. Now I want to show image from documents directory to imageview. How to do that? Any idea?
sample code:
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
-(void)loadimage{
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"your image-name"];
UIImageView *myimage=[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)];
myimage.image=[UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubView:myimage];
[myimage release];
}
NSString *str = [NSString stringWithFormat:#"%#.jpg",[YourImageArray objectAtIndex:imageCounter]];
or
NSString *str=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:#"YourImageName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullImgNm=[documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:str]];
[ImageView setImage:[UIImage imageWithContentsOfFile:fullImgNm]];
Hope Your Helpfull
NSString *docDirPath = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] objectAtIndex:0];
NSString *filePath = [docDirPath stringByAppendingFormat:#"myFile.png"];
UIImage *image = [UIImage imageWithContentsOfFile:filePath];
[imageView setImage:image];
If the entire path is stored in the sqlite then you just need to use this
NSString *imapeFilePath = PATH_FROM_DATABASE;
self.imageView.image = [UIImage imageWithContentsOfFile:imapeFilePath];
if the file name is stored in the database then use the following
NSString *imapeFilePath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:YOUR_IMAGE_NAME];
self.imageView.image = [UIImage imageWithContentsOfFile:imapeFilePath];

SQLite issue: sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) not working

-(void)myDatabaseFunction
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"HHAuditToolDatabase.sqlite"];
if (sqlite3_open([writableDBPath UTF8String], &database) == SQLITE_OK){
NSLog(#"opening db");
NSString *keyValue;
NSString *sqlStr = #"SELECT * FROM HHAuditTable";
//following if() not working dude!!!!
//its working with !=SQLITE_OK
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
sqlite3_stmt *addStmt = nil;
if(sqlite3_prepare_v2(database,[sqlStr UTF8String], -1, &addStmt, NULL) != SQLITE_OK){
NSLog(#"%#",sqlStr);
while (sqlite3_step(addStmt) == SQLITE_ROW) {
const unsigned char *querry_returns = sqlite3_column_text(addStmt, 0);
keyValue = [[NSString alloc]initWithUTF8String:(char *) sqlite3_column_text(addStmt, 0)];
}
NSLog(#"value from DB = %#",keyValue);
That if() with comment doesn't work....Some have a cure!!! i have been on it for last 3 hrs....please come up with a soln
You are opening the database twice. You should have to close the database connection and then you have to open the database again. That is why it is not working.
Hay you can use my code its working fine for me:-
(void)myDatabaseFunction {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success) {
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"flipsy.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
NSString *sql = #"SELECT * FROM HHAuditTable";
NSInteger *intvalue;
result = [[NSMutableArray alloc] init];
// NSLog(#"sql--------->%#",sql);
const char *sqlStatement = [sql UTF8String];
//if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
if(sqlite3_prepare_v2(database, sqlStatement, -1, &selectstmt , NULL)!= SQLITE_OK) {
}
else {
//NSLog(#"%#",dataTypeArray);
for(int i=0;i<[dataTypeArray count];i++) {
temp = [[NSMutableArray alloc] init];
[result addObject:temp];
// [temp release];
}
while(sqlite3_step(selectstmt) == SQLITE_ROW) {
for(int i=0;i<[dataTypeArray count];i++) {
switch( [[dataTypeArray objectAtIndex:i] integerValue] ) {
case 0:
intvalue = (NSInteger *)sqlite3_column_int(selectstmt,i);
strvalue = [NSString stringWithFormat:#"%d",intvalue];
[[result objectAtIndex:i] addObject:(NSNumber *)strvalue];
break;
case 1:
[[result objectAtIndex:i] addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, i)]];
break;
case 2:
blob = [[NSData alloc] initWithBytes:sqlite3_column_blob(selectstmt, i) length:sqlite3_column_bytes(selectstmt, i)];
[[result objectAtIndex:i] addObject:blob];
[blob autorelease];
break;
default:
defaultValue=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, i)];
break;
}//switch
}//for(int i=0;i<[dataTypeArray count];i++)
}//while(sqlite3_step(selectstmt) == SQLITE_ROW)
//}//else
//sqlite3_close(database);
sqlite3_finalize(selectstmt);
[temp release];
}//if (sqlite3_open([dbPath UTF
}
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"flipsy.sqlite"];
}
Please let me know if any clarification needed

Searching SQLite3 DB in iPhone from input given in UITextfield

I am fairly new to iOS development. I am trying to build application which searches given search term in sqllite3 DB. I am having trouble with binding parameter to that sql statement.Following is my code to read data from database.
-(void) readPlayersFromDatabase
{
NSString * strTemp=[[NSString alloc]init];
strTemp=#"ben";
sqlite3 *database;
players = [[NSMutableArray alloc] init];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
char *sqlStatement = "SELECT * FROM Player WHERE LENGTH (lastname)>0 AND LENGTH (firstname)>0 AND ( lastname LIKE '%?%' OR firstname LIKE'%?%' OR Height LIKE '%?%' OR Weight LIKE '%?%') ORDER BY lastname,firstname";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
sqlite3_bind_text(compiledStatement, 1, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 2, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 3, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
sqlite3_bind_text(compiledStatement, 4, [strTemp UTF8String],-1, SQLITE_TRANSIENT );
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
NSString *playerId = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *playerName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
Player *temp = [[Player alloc] initWithID:playerId name:playerName];
[players addObject:temp];
[temp release];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
All I am getting at the end is name of player which has ? in their name. Can anyone help me out here. Can you also tell me how can I connect UITextfield input to the strTemp in above code ?
Thanks.
What do you want to do exactly? You can send as a parameter to your readPlayersFromDatabase method to your UITextfield input.
Here is my method to select command: I had a class which is called DBOperations. I hope that helps
+ (int) getUserID{
//check DB
if (![DBOperations checkDB])
{
NSString *msgAlert = #"can not access db file.";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Connection error" message:msgAlert
delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
return 0;
}
[DBOperations open];
int _userID = 1;
const char* sql = " select id from Oyuncu ORDER BY id desc";
if (sqlite3_prepare_v2(database, sql, -1, &hydrate_statement, NULL) != SQLITE_OK) {
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
if (sqlite3_step(hydrate_statement)==SQLITE_ROW)
{
_userID= sqlite3_column_int(hydrate_statement,0);
NSLog(#"%d",_userID);
}
// Execute the query.
sqlite3_finalize(hydrate_statement);
return _userID;
[DBOperations close];
}
+(BOOL) checkDB {
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"dbOyun.db"];
BOOL success = [fileManager fileExistsAtPath:writableDBPath];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return true;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"dbOyun.db"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
return success;
}
+ (void) open{
//check db validity
NSString *dbPath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
dbPath = [documentsDirectory stringByAppendingPathComponent:#"dbOyun.db"];
if (sqlite3_open([dbPath UTF8String], &database) != SQLITE_OK) {
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
}
}

Getting error while trying to fetch and insert data into SQLite database

I am creating an application where I am using SQLite database to save data. But when I run my application I get the following errors:
#interface TDatabase : NSObject {
sqlite3 *database;
}
+(TDatabase *) shareDataBase;
-(BOOL) createDataBase:(NSString *)DataBaseName;
-(NSString*) GetDatabasePath:(NSString *)database;
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database;
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1;
#end
#import "TDatabase.h"
#import <sqlite3.h>
#implementation TDatabase
static TDatabase *SampleDataBase =nil;
+(TDatabase*) shareDataBase{
if(!SampleDataBase){
SampleDataBase = [[TDatabase alloc] init];
}
return SampleDataBase;
}
-(NSString *)GetDatabasePath:(NSString *)database1{
[self createDataBase:database1];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:database1];
}
-(BOOL) createDataBase:(NSString *)DataBaseName{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DataBaseName];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return success;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:DataBaseName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!!!" message:#"Failed to create writable database" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
return success;
}
-(NSMutableArray *) getAllDataForQuery:(NSString *)sql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
NSMutableArray *alldata;
alldata = [[NSMutableArray alloc] init];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
NSString *query = sql;
if((sqlite3_prepare_v2(database,[query UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSMutableDictionary *currentRow = [[NSMutableDictionary alloc] init];
int count = sqlite3_column_count(statement);
for (int i=0; i < count; i++) {
char *name = (char*) sqlite3_column_name(statement, i);
char *data = (char*) sqlite3_column_text(statement, i);
NSString *columnData;
NSString *columnName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
if(data != nil)
columnData = [NSString stringWithCString:data encoding:NSUTF8StringEncoding];
else {
columnData = #"";
}
[currentRow setObject:columnData forKey:columnName];
}
[alldata addObject:currentRow];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return alldata;
}
-(void*) inseryQuery:(NSString *) insertSql forDatabase:(NSString *)database1{
sqlite3_stmt *statement = nil ;
NSString *path = [self GetDatabasePath:database1];
if(sqlite3_open([path UTF8String],&database) == SQLITE_OK )
{
if((sqlite3_prepare_v2(database,[insertSql UTF8String],-1, &statement, NULL)) == SQLITE_OK)
{
if(sqlite3_step(statement) == SQLITE_OK){
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return insertSql;
}
NSString *sql = #"select * from Location";
const location = [[TDatabase shareDataBase] getAllDataForQuery:sql forDatabase:#"journeydatabase.sqlite"];//1
NSString* insertSql = [NSString stringWithFormat:#"insert into Location values ('city','name','phone')"];//2
const insert =[[TDatabase shareDataBase] inseryQuery:insertSql forDatabase:#"journeydatabase.sqlite"];//3
in line no 1,2,3 I get the same error:
initializer element is not constant
What might be the problem?
#rani writing your own methods to deal with sqlite database is very painstaking. You should use fmdb wrapper class or use core data. I personally prefer fmdb. Initially I was doing the same way you were. I found about fmdb here. After using it I had to write very little code whenever I have to deal With sqlite db.

the SQLiteBooks sample code is missing

I find this link everywhere for SQLite sample code (http://developer.apple.com/library/ios/#samplecode/SQLiteBooks/index.html) but either it has been removed or changed to another location.. I couldn't find it in google searches.. Does anyone know any other link to the code or any other good sample code for SQLite?
May be this is useful to you.
http://www.switchonthecode.com/tutorials/using-sqlite-on-the-iphone
http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/
http://www.icodeblog.com/2008/08/19/iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1/
You can use this class and send query in this class and get all functionality of sqlite using this class
.h
#import <Foundation/Foundation.h>
#import "sqlite3.h"
#interface DBLib : NSObject {
sqlite3 *database;
NSString *path;
}
- (NSString *)getDatabasePath:(NSString*)DBName;
- (void)createEditableCopyOfDatabaseIfNeeded:(NSString*)DBName;
- (void)initializeDatabase:(NSString*)DBName;
-(NSMutableArray*)GetListBySQL:(NSString*)SQL;
-(BOOL)UpdateData:(NSMutableDictionary*)objDic :(NSString*)PrimaryKey :(NSString*)TABLE_NAME;
-(BOOL)deleteQuery:(NSString *)query;
#end
.m
#import "DBLib.h"
#implementation DBLib
#pragma mark Database methods
- (NSString *)getDatabasePath:(NSString*)DBName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ;
NSString *documentsDirectory = [paths objectAtIndex:0] ;
return [documentsDirectory stringByAppendingPathComponent:DBName];
}
// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded:(NSString*)DBName {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DBName];
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:DBName];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[error localizedDescription] ]];
NSAssert1(0, #"%#", errString);
}
}
// Open the database connection and retrieve minimal information for all objects.
- (void)initializeDatabase:(NSString*)DBName {
// The database is stored in the application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
path = [documentsDirectory stringByAppendingPathComponent:DBName];
NSStringEncoding enc = [NSString defaultCStringEncoding];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
{
//TRUE
NSLog(#"Successfully opened-sqlite3");
}
else
{
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSLog(#"closed");
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[NSString stringWithCString:sqlite3_errmsg(database) encoding:enc] ]];
NSAssert1(0, #"%#", errString);
// Additional error handling, as appropriate...
}
}
-(NSMutableArray*)GetListBySQL:(NSString*)SQL
{
[self initializeDatabase:#"DBNAME"];
NSMutableArray* Array;
Array=[[NSMutableArray alloc]init];
NSStringEncoding enc = [NSString defaultCStringEncoding];
sqlite3_stmt *select_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &select_statement, NULL) != SQLITE_OK) {
NSString *errString = [NSString stringWithFormat:#"%#", [#"Fail" stringByReplacingOccurrencesOfString:#"#" withString:[NSString stringWithCString:sqlite3_errmsg(database) encoding:enc] ]];
NSAssert1(0, #"%#", errString);
}
int columncount=sqlite3_column_count(select_statement);
NSMutableDictionary* dic;
while (sqlite3_step(select_statement) == SQLITE_ROW)
{
dic=[[NSMutableDictionary alloc]init];
for(int j=0;j<columncount;j++)
{
if(sqlite3_column_text(select_statement, j)!=nil)
[dic setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(select_statement, j)] forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(select_statement,j)]];
else
[dic setObject:#"" forKey:[NSString stringWithUTF8String:(char *)sqlite3_column_name(select_statement,j)]];
}
[Array addObject:dic];
[dic release];
}
sqlite3_finalize(select_statement);
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray: Array];
[Array release];
return arr;
}
//Method for Datbase
-(BOOL)UpdateData:(NSMutableDictionary*)objDic :(NSString*)PrimaryKey :(NSString*)TABLE_NAME
{
NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
[self initializeDatabase:DBNAME];
NSString* SQLColumns=#"";
NSString* SQLValues=#"";
NSString* SQL=#"";
//Chekc Wheather Insert or update?
BOOL IsNew=NO;;
if([[objDic valueForKey:PrimaryKey] intValue]==0)
{
IsNew=YES;
}
NSArray* Keys=[objDic allKeys];
NSLog(#"%#",Keys);
if(IsNew)
{
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
SQLColumns=[NSString stringWithFormat:#"%#%#,",SQLColumns,[Keys objectAtIndex:i]];
SQLValues=[NSString stringWithFormat:#"%#?,",SQLValues];
}
}
if([SQLColumns length]>0)
{
SQLColumns=[SQLColumns substringToIndex:[SQLColumns length]-1];
SQLValues=[SQLValues substringToIndex:[SQLValues length]-1];
}
SQL=[NSString stringWithFormat:#"INSERT INTO %# (%#) Values(%#)",TABLE_NAME,SQLColumns,SQLValues];
}
else
{
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
SQLColumns=[NSString stringWithFormat:#"%#%#=?,",SQLColumns,[Keys objectAtIndex:i]];
}
}
if([SQLColumns length]>0)
{
SQLColumns=[SQLColumns substringToIndex:[SQLColumns length]-1];
}
SQL=[NSString stringWithFormat:#"UPDATE %# SET %# WHERE %#=?",TABLE_NAME,SQLColumns,PrimaryKey];
//NSLog(sql);
}
sqlite3_stmt *insert_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &insert_statement, NULL) != SQLITE_OK) {
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
NSLog(#"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
int intBindIndex=1;
for(int i=0;i<Keys.count;i++)
{
if(![[Keys objectAtIndex:i] isEqual:PrimaryKey])
{
sqlite3_bind_text(insert_statement,intBindIndex,[[objDic valueForKey:[Keys objectAtIndex:i]] UTF8String],-1, SQLITE_STATIC);
intBindIndex++;
}
}
if(!IsNew)
{
sqlite3_bind_text(insert_statement,Keys.count,[[objDic valueForKey:PrimaryKey] UTF8String],-1, SQLITE_STATIC);
}
int result;
result=sqlite3_step(insert_statement);
if(IsNew)
{
[objDic setObject:[NSString stringWithFormat:#"%d",sqlite3_last_insert_rowid(database)] forKey:PrimaryKey];
}
sqlite3_finalize(insert_statement);
[pool release];
NSLog(#"result:%d",result);
if(result==SQLITE_DONE)
return YES;
else
return NO;
}
-(BOOL)deleteQuery:(NSString *)query
{
NSAutoreleasePool* pool=[[NSAutoreleasePool alloc]init];
[self initializeDatabase:DBNAME];
NSString* SQL=#"";
SQL=[NSString stringWithString:query];
sqlite3_stmt *insert_statement=nil;
if (sqlite3_prepare_v2(database, [SQL UTF8String], -1, &insert_statement, NULL) != SQLITE_OK) {
//NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
NSLog(#"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
int result;
result=sqlite3_step(insert_statement);
sqlite3_finalize(insert_statement);
[pool release];
NSLog(#"result:%d",result);
if(result==SQLITE_DONE)
return YES;
else
return NO;
}
#end