Get data from database. - iphone

Ok, I am able to connect to the mysql database from my iPhone app, I have set it up in a tableview. So when I call the didSelectRow method it stores the users Id number, not the indexRow number. My question is how can I use that stored id to retrieve the rest of the information, so when the row is pressed it brings up the rest of that users particular Information. I know I am not showing any code here that is because I'm writing this from my iPad, so I hope you cam follow what im trying to do and help. Thanks.

I can help u in one way that u have to store the array coming from the data base in an array in appdel u can call that array at any time where we want sample code is here
this is the array in appdb
NSMutableArray *fruit_details;
call one method in Appdb
[self readStudentFromDatabase];
then write the code here in that method
NSArray *documentpaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentpaths objectAtIndex:0];
databasePath = [documentDir stringByAppendingPathComponent:databaseName];
fruit_details=[[NSMutableArray alloc]init];
//open the database from the users filesystem
if(sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK)
{
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement ="select * from stu";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement , NULL)== SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while (sqlite3_step(compiledStatement)==SQLITE_ROW)
{
NSString *aName =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,0)];
NSString *amarks=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,1)];
NSString *arank =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,2)];
NSString *aaddr =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,3)];
NSString *aemail =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,4)];
NSString *aphno =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,5)];
NSString *aage =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,6)];
NSString *asex =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,7)];
NSString *adate =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,8)];
NSString *aimage=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];
// // Create a new animal object with the data from the database
//animal *animal_object=[[animal alloc]initWithName:aName description:arollNO url:amarks];
//add the animal object to the animal ar
//[animals addObject:animal_object];
temp=[[NSMutableArray alloc]init];
[temp addObject:aName];
[temp addObject:amarks];
[temp addObject:arank];
[temp addObject:aaddr];
[temp addObject:aemail];
[temp addObject:aphno];
[temp addObject:aage];
[temp addObject:asex];
[temp addObject:adate];
[temp addObject:aimage];
[fruit_details addObject:temp];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
I think this may help u.....

Is stored id what you get from the db? My understanding is that when user select a row, you want to go to a new view and fetch the corresponding information from the db using that stored id.

Related

UITableView not getting populated with sqlite database column

Here's the code of a method I used to populate UITableView with the contents of a column in sqlite database. However, this is giving no errors at run-time but still does not give any data in UITableView. If anyone could help, it'll be highly appreciated.
- (void)viewDidLoad{
[super viewDidLoad];
self.title = #"Strings List";
UITableViewCell *cell;
NSString *docsDir;
NSArray *dirPaths;
sqlite3_stmt *statement;
// 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:#"strings.sqlite"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString * query =
#"SELECT string FROM strings";
const char * stmt = [query UTF8String];
if (sqlite3_prepare_v2(contactDB, stmt, -1,&statement, NULL)==SQLITE_OK){
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *string = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 0)];
cell.textLabel.text = string; }
}
else NSLog(#"Failed");
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
}
I recommend you to read through Table View Programming Guide.
Most of the sequence you put in the viewDidLoad normally is placed in
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath;
that pretty complex method u are using, when u have all the delegate methods for table view which is just like putting butter on bread.
Try My Answer from this Link
Let me know if it worked !!!!
Cheers
if You are using simulator for testing purpose then delete your previous build and install app again. It fetch SQL file from document directory. So please try this and let me know. Thanks
Have you check if the problem is with you tableview or database?
Are you able to fetch data from database?Check if you are missing any method to connect sqlite in code.

iPhone - Trying to Copy sqlite Database to Documents Directory - copies blank version

I have an sqlite database called 'ProductDatabase.sql', which I have copied into my applications project directory:
/Users/jacknutkins/Documents/TabbedDietApp/TabbedDietApp/ProductDatabase.sql
In the applications app delegate class I have this piece of code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Set-up some globals
m_DatabaseName = #"ProductDatabase.sql";
//Get the path to the documents directory and append the databaseName
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
m_DatabasePath = [documentsDirectory stringByAppendingPathComponent:#"ProductDatabase.sql"];
//Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];
//Query the databse for all animal records and construct the "animals" array
[self readProductsFromDatabase];
....
At this point:
m_DatabasePath = '/Users/jacknutkins/Library/Application Support/iPhone Simulator/5.0/Applications/6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B/Library/ProductDatabase.sql'
Here is the code for the other 2 methods:
- (void) checkAndCreateDatabase {
NSError * error;
//Check if the database has been saved to the users phone, if not then copy it over
BOOL l_Success;
//Create a file manager object, we will use this to check the status
//of the databse and to copy it over if required
NSFileManager *l_FileManager = [NSFileManager defaultManager];
//Check if the database has already been created in the users filesystem
l_Success = [l_FileManager fileExistsAtPath:m_DatabasePath];
//If the database already exists then return without doing anything
if(l_Success)
return;
//If not then proceed to copy the database from the application to the users filesystem
//Get the path to the database in the application package
NSString *l_DatabasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:m_DatabaseName];
//Copy the database from the package to the usrrs filesystem
[l_FileManager copyItemAtPath:l_DatabasePathFromApp toPath:m_DatabasePath error:&error];
}
If I perform some NSLogs here:
l_DatabasePathFromApp = /Users/jacknutkins/Library/Application Support/iPhone Simulator/5.0/Applications/6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B/TabbedDietApp.app/ProductDatabase.sql
and:
error = Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x6b6d060 {NSFilePath=/Users/jacknutkins/Library/Application Support/iPhone Simulator/5.0/Applications/6D5BBE3A-BC9A-4C44-B089-FABA27CFFF4B/TabbedDietApp.app/ProductDatabase.sql, NSUnderlyingError=0x6b6cfa0 "The operation couldn’t be completed. No such file or directory"}
I'm not sure what file it is it can't find here..
- (void) readProductsFromDatabase {
//Init the products array
m_Products = [[NSMutableArray alloc] init];
NSLog(#"%#", m_DatabasePath);
//Open the database from the users filessystem
if(sqlite3_open([m_DatabasePath UTF8String], &database) == SQLITE_OK) {
//Set-up the SQL statement and compile it for faster access
const char *sqlStatement = "select * from products";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
{
NSLog(#"Success..");
//Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
//Read the data from the results row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aCategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aCalories = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *aFat = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *aSaturates = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *aSugar = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *aFibre = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
NSString *aSalt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 8)];
NSString *aImageURL = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)];
NSLog(#"Delegate");
NSString *aNote = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 10)];
NSUInteger myInt = sqlite3_column_int(compiledStatement, 11);
NSString *aServes = [NSString stringWithFormat:#"%d", myInt];
//Create a new animal object with the data from the database
Product *l_Product = [[Product alloc] initWithName:aName category:aCategory calories:aCalories fat:aFat saturates:aSaturates sugar:aSugar fibre:aFibre salt:aSalt imageURL:aImageURL note:aNote serves:aServes];
//Add the animal object to the animals array
[m_Products addObject:l_Product];
}
}
//Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
database is declared in the .h file as follows:
//Setup the database object
sqlite3 *database;
In the above method, the line:
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
does not evaluate to SQLITE_OK, because the database I try to copy to the documents directory is blank.
I have tried cleaning and building, deleting the blank copy of the database and re-running etc but it continues to copy a blank database every time.
I've googled this several times and I've tried everything I can find with no success..
Any help would be hugely appreciated.
Jack
EDIT
If I perform 'select * from products' from the terminal window on the database in the project directory I return the expected results.
I had forgotten to include the database file in the target membership by clicking on the check box in the file inspector tab.

check if data exists before insert into sqlite database for iphone

I want to do insert data into sqlite..While inserting i m getting duplications in my code..i saw the questions related to it and i m getting clear about that..anyone just help me with this code to check data is present before insert into database...
- (IBAction)AddtoFavourites:(id)sender {
sqlite3 *database;
dbName=#"dataTable.sqlite";
NSArray *documentpath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdir=[documentpath objectAtIndex:0];
dbPath=[documentdir stringByAppendingPathComponent:dbName];
if(sqlite3_open([dbPath UTF8String], &database)==SQLITE_OK){
//I want to check data it exists already into database....
NSString *sqlStatement=[NSString stringWithFormat:#"insert into Persons(PersonName,CompanyName,ImgUrl)values(\"%#\",\"%#\",\"%#\")",model.personName,model.companyName,model.imgurl];
const char *insertSQL=[sqlStatement UTF8String];
char *errMsg;
sqlite3_exec(database, insertSQL, NULL,NULL,&errMsg);
NSLog(#"Add to Favourites");
}
}
First use select query for any of column as:
const char *sqlStatement = "SELECT PersonName FROM Persons";
i guess you would have assigned sqlStatement into compiledStatement
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
[dataArray addObject:aName];
NSLog(#"%#",aName);
}
Put a check on this

How to use sqlite3_column_blob with NSData

How to use sqlite3_column_blob with NSData what parameter I need to pass
In my iPhone App I want to retrive image stored in NSData format in sqlite database in BLOB datatype
for retriving it
//select query
NSString *selectQuery = [NSString stringWithFormat:#"select image_column from tbl_image where id=1"];
NSArray *arraySelect = [database executeQuery:selectQuery];
//displaying image
NSData *imageData = [[arraySelect objectAtIndex:0] valueForKey:#"image_column"];
self.img3=[UIImage imageWithData:imageData];
imageView.image=img3;
from above code I am not able to display image
so please help and suggest
thanks
sqlite *database;
sqlite3_stmt *Stmt;
sqlite3_open([[self getDBPath] UTF8String],&database)
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"XXX.sqlite"];
}
NSData*thumbnailData;
//Inserting Thumbnail Data
NSString *lSQL = [NSString stringWithFormat:#"insert into Table(Thumbnail1) values(?)"];
if(sqlite3_prepare_v2(database, [lSQL UTF8String], -1, &Stmt, NULL) == SQLITE_OK)
{
sqlite3_bind_blob(Stmt, 1,[thumbnailData bytes], [thumbnailData length], NULL);
sqlite3_step(Stmt);
sqlite3_reset(Stmt);
if(Stmt)
sqlite3_finalize(Stmt);
}
//Fetching Thumbnail Data
NSString *lSQL = [NSString stringWithFormat:#"select Thumbnail1 from table"];
if(sqlite3_prepare_v2(database, [lSQL UTF8String], -1, &Stmt, NULL) == SQLITE_OK)
{
while(sqlite3_step(Stmt) == SQLITE_ROW)
{
NSString *myColNameNSString = [NSString stringWithFormat:#"%s", sqlite3_column_name(Stmt)];
if ([myColNameNSString isEqualToString:#"Thumbnail1"])
{
thumbnailData = [[NSData alloc] initWithBytes:sqlite3_column_blob(Stmt) length:sqlite3_column_bytes(Stmt)];
}
}
}
Hey, I don't what are your project requirements. I would not use BLOB unless it's required to.
reason is you are storing image file into sqlite, everytime you have to use the file you have access the database, process the file and use. which will be fairly easy and simple in terms of number of threads you are running if you use images directly form the disk. give a thought about it. Good Luck

iPHONE SDK- sqlite , how do i do an insert statement

i have a database that is in the documents directorys of the
Application/iPhoneSimulator/3.2/Applications/etc/Documents
I have this code under my method
databaseName = #"database.sql";
NSArray *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory.NSUserDomainMask,YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
How do i do an insert with a variable/ array .
Something like
"INSERT INTO TABLE (COLUMN) VALUES ('%#'),[appDelegate.variable objectAtIndex:0];
I insist you to go through this question.
First of all copy the database from main bundle to your application's document dir.
You can follow below code to implement it.
NSString *databaseFile=[[NSBundle mainBundle] pathForResource:kDataBaseName ofType:kDataBaseExt];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *dbPath=[basePath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#",kDataBaseName,kDataBaseExt]];
NSFileManager *fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:dbPath]){
[fm copyItemAtPath:databaseFile toPath:dbPath error:nil];
}
[fm release];
self.dataBasePath=dbPath;
I am supplying you directly my project code. Please add comment if any doubts.
I have added comments for the explanation.
// function with multiple arguments which is going to be used for inserting into table.
+(void)insertBuilding:(NSString*)BName streetNo:(NSInteger)streetNo streetName:(NSString*)streetName streetDir:(NSString*)streetDir muni:(NSString*)muni province:(NSString*)province bAccess:(NSString*)bAccess bType:(NSString*)bType amnity:(NSString*)amnity latitude:(NSString*)latitude longitude:(NSString*)longitude imageName:(NSString*)imageName {
// application delegate where I have saved my database path.
BuildingLocatorAppDelegate *x=(BuildingLocatorAppDelegate *)[[UIApplication sharedApplication]delegate];
sqlite3 *database; // database pointer
// verifying if database successfully opened from path or not.
// you must open database for executing insert query
// i have supplied database path in argument
// opened database address will be assigned to database pointer.
if(sqlite3_open([[x dataBasePath] UTF8String],&database) == SQLITE_OK) {
// creating a simple insert query string with arguments.
NSString *str=[NSString stringWithFormat:#"insert into buildingDtl(b_name,streetNo,streetName,streetDir,muni,province,b_access,b_type,aminity,latitude,longitude,b_image) values('%#',%i,'%#','%#','%#','%#','%#','%#','%#','%#','%#','%#')",BName,streetNo,streetName,streetDir,muni,province,bAccess,bType,amnity,latitude,longitude,imageName];
// converting query to UTF8string.
const char *sqlStmt=[str UTF8String];
sqlite3_stmt *cmp_sqlStmt;
// preparing for execution of statement.
if(sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL)==SQLITE_OK) {
int returnValue = sqlite3_prepare_v2(database, sqlStmt, -1, &cmp_sqlStmt, NULL);
((returnValue==SQLITE_OK) ? NSLog(#"Success") : NSLog(#"UnSuccess") );
// if NSLog -> unsuccess - that means - there is some problem with insert query.
sqlite3_step(cmp_sqlStmt);
}
sqlite3_finalize(cmp_sqlStmt);
}
sqlite3_close(database);
// please don't forget to close database.
}
+(NSString *)stringWithFormat:(NSString *)format parameters:...];
NSString sql = [NSString stringWithFormat:#"INSERT INTO table VALUES('%#')", #"Hello, world!"];
sqlite3_....
Use either prepared statements in combination with the bind_*() functions (e.g. bind_text()) or the mprintf() function to insert strings, see this question for details.
To get a raw C-string you can pass to these functions use -UTF8String or -cStringUsingEncoding: on a NSString.