im Working on inserting IMAGE in to Database using sqlite in Xcode 4.6 ,i just wanted to insert a textfield and uiimageview(having dynamically generated barcode image).
unfortunately im getting " Error is: out of memory "
hear is the code I'm using ,plz let me know where my mistake is & Let me know for more details
* 1. Database creation*
-(void)createoropendb {
NSArray *path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docpath =[path objectAtIndex:0];
dbpathstring =[docpath stringByAppendingPathComponent:#"DataBase.db"];
char *error;
NSFileManager *filemanager =[NSFileManager defaultManager];
if (![filemanager fileExistsAtPath:dbpathstring])
{
const char *dbpath =[dbpathstring UTF8String];
if (sqlite3_open(dbpath, &barcodeDB) == SQLITE_OK)
{
const char *sql_start ="CREATE TABLE IF NOT EXISTS DBTABLE1(NAME TEXT UNIQUE,IMAGEURL BLOB)";
NSLog(#"db created");
sqlite3_exec(barcodeDB, sql_start,NULL,NULL, &error);
sqlite3_close(barcodeDB);
}
}
}
* 2.button to insert data*
- (IBAction)savedata:(id)sender {
UIImage *image =imageView.image;
NSData *imageData=UIImagePNGRepresentation(image);
[self SaveImagesToSql: imageData.bytes:Uimagetext.text];
}
* 3.method to insert data*
- (void) SaveImagesToSql: (NSData*) imgData :(NSString*) mainUrl {
const char* sqliteQuery = "INSERT INTO DBTABLE1(NAME,IMAGEURL) VALUES (?, ?)";
sqlite3_stmt* statement;
if( sqlite3_prepare_v2(barcodeDB, sqliteQuery, -1, &statement, NULL) == SQLITE_OK )
{
sqlite3_bind_text(statement, 1,[mainUrl UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 2,[imgData bytes],[imgData length], SQLITE_TRANSIENT);
sqlite3_step(statement);
NSLog( #"Saved image successfully" );
}
else
{
NSLog( #"SaveBody: Failed from sqlite3_prepare_v2. Error is: %s",sqlite3_errmsg(barcodeDB) );
}
// Finalize and close database.
sqlite3_finalize(statement);
}
The return code (which is not SQLITE_OK) is undoubtedly returning SQLITE_MISUSE, meaning that you're trying to use a database that you haven't opened yet. Your createoropendb is creating and opening if the database doesn't exist, but if it does exist, you're not opening it (and even if it did exist, you're closing it after creating it).
Bottom line, if the database is not opened when you call sqlite3_prepare, that function will return SQLITE_MISUSE, any calls to sqlite3_errmsg will return a misleading "Out of memory" text message.
Related
I want the application which work online as well as offline example WhatsApp. For that i have to sync data from web service then store it in sqlite db file.
And I want that whoever installs this application would have a slot for automatic saving data in database file. Do I have to add db file from iTunes?
I don't want to use core data concept.
Is it possible it will be there in with application?
Like in Android there is something called cache memory where db file is stored so there is any sort of provision for it in ios?
+(int)insert_In_AdverImage:(NSString *)strid ImageName:(NSString *)strimg Isshow:(NSString *)strshow LastUpdateId:(NSString *)date isdelete:(NSString *)isdelete Sortorder:(int)sortOrder{
sqlite3 *database;
int retValue = 0;
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSString *tempSQL = [[NSString alloc] initWithFormat:#"INSERT INTO ADVERIMAGE(advId ,advimg ,isshow ,LastUpdateId ,IsDelete ,SortorderId ) VALUES ('%#', '%#', '%#', '%#', '%#', '%d')", strid, strimg, strshow, date, isdelete, sortOrder];
const char *sqlStatement = [tempSQL cStringUsingEncoding:NSUTF8StringEncoding];
sqlite3_stmt *compiledStatement;
sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL);
sqlite3_step(compiledStatement);
retValue = (int)sqlite3_last_insert_rowid(database);
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
return retValue;
}
works well. But still the db file in app bundle is empty.i got it that whenever we insert something it will be inserted in document and if we have to see the inserted data we have to get it from document
Thanks in advance
Any Help would be appreciated.
Yes. Possible.
You can store SQlite DB in your applications's Document Directory. You need to write your own Query to Open DB, Insert Data, Retrieve Data from DB.
Check out following tutorial for your requirement : http://www.appcoda.com/sqlite-database-ios-app-tutorial/
Hope it helps.
Following function is used to Insert :
NSArray *docsDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [docsDirectory objectAtIndex:0];
NSString *databasePath = [docPath stringByAppendingPathComponent:#"Database.sqlite"];
sqlite3 *dbHandler;
const char *dbPath = [databasePath UTF8String];
sqlite3_stmt *sqlStmt;
if(sqlite3_open(dbPath, &dbHandler) == SQLITE_OK)
{
if (sqlite3_prepare_v2(dbHandler, [queryString UTF8String], -1, &sqlStmt, NULL) == SQLITE_OK)
{
if (sqlite3_step(sqlStmt) == SQLITE_DONE)
{
NSLog(#"Data Inserted");
}
else
{
NSLog(#"Not inserted");
}
}
else
{
NSLog(#"Failed to Insert data -InsertDataFunc");
}
sqlite3_close(dbHandler);
}
////this method use for show data and that works
NSString *databasePath =[[[NSBundle mainBundle] bundlePath]stringByAppendingPathComponent:#"images.db"];
if(sqlite3_open([databasePath UTF8String], &db)==SQLITE_OK){
const char *sql = "SELECT * FROM IMAGEDATA";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
NSData *imageData = [[NSData alloc] initWithBytes:sqlite3_column_blob(sqlStatement, 1) length: sqlite3_column_bytes(sqlStatement, 1)];
imagesfromdb =[UIImage imageWithData:imageData];
NSLog(#"IMAGE :::%#",imagesfromdb);
[databaseimage addObject:imagesfromdb];
//imageData is saved favicon from website.
}
}
}
/////this method use for insert data.
const char *dbpath = [databasePath UTF8String];
if(sqlite3_open(dbpath, &database)==SQLITE_OK)
{
NSData *imageData = UIImageJPEGRepresentation(chosenImage, 1);
const char* sqliteQuery = "INSERT INTO IMAGEDATA (NAME, IMAGE) VALUES (?, ?)";
//sqlite3_stmt* statement;
if( sqlite3_prepare_v2(database, sqliteQuery, -1, &statement, NULL) == SQLITE_OK )
{
sqlite3_bind_text(statement, 1, [fileName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_blob(statement, 2, [imageData bytes], (int)[imageData length], SQLITE_TRANSIENT);
sqlite3_step(statement);
}
else NSLog( #"SaveBody: Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(database) );
// Finalize and close database.
sqlite3_finalize(statement);
}
this method not working i cant understand but this method show data until i close the app. but after that the data will be gone and didnt save in db file
All the assets inside mainBundle of your app sandbox have readonly property. That's why in your case you are able to read the data but not modify it. So you should first copy your database file to DocumentDirectory which has readwrite access, and then you will be able to perform the write operation in that db. Check this question to understand how to copy database file from mainBundle to DocumentDirectory.
How to copy sqlite database when application is launched in iOS?
You can follow this Tutorial as well to understand all steps
I'm insert data into sqlite database and I've seen NSLog(#"DONE") on my console result, but I don't see the data update in my sqlite database file. Pls help me !!!
Here my code to save data:
- (void)saveData:(NSString *)_Id
{
sqlite3_stmt *statement;
NSString *_databasePath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.db"];
const char *dbpath = [_databasePath UTF8String];
if (sqlite3_open(dbpath, &db) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO MyTable (id) VALUES (\"%#\")", _Id];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(db, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"DONE");
} else {
NSLog(#"Failed to add contact");
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}
You are opening the database in your bundle. The bundle is read-only on the device. You must copy the database to your Documents folder (if it doesn't exist there already) and open it from there.
Also be aware that you're dealing with multiple copies of the database (the one in your project, the one in the bundle and now the one in the device/simulator's Documents folder). Make sure you're checking for the inserted record in the correct database (the one in Documents)
As an aside, you should also check to see that sqlite3_prepare_v2 returned SQLITE_OK and if not, log sqlite3_errmsg.
You should also use ? placeholder in your SQL and bind values using sqlite3_bind_text (or, if it's possibly nil, sqlite_bind_null):
- (void)saveData:(NSString *)_Id
{
sqlite3_stmt *statement;
NSString *bundlePath = [[[NSBundle mainBundle] resourcePath ] stringByAppendingPathComponent:#"data.db"];
NSString *documentsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *documentsPath = [documentsFolder stringByAppendingPathComponent:#"data.db"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:documentsPath isDirectory:NO]) {
NSError *error;
if (![fileManager copyItemAtPath:bundlePath toPath:documentsPath error:&error]) {
NSLog(#"database copy failed: %#", error);
}
}
const char *dbpath = [documentsPath UTF8String];
if (sqlite3_open(dbpath, &db) == SQLITE_OK) {
const char *insertSql = "INSERT INTO MyTable (id) VALUES (?)";
if (sqlite3_prepare_v2(db, insertSql, -1, &statement, NULL) != SQLITE_OK) {
NSLog(#"prepare error: %s", sqlite3_errmsg(db));
}
// bind a value to the ? placeholder in the SQL
if (_Id) {
if (sqlite3_bind_text(statement, 1, [_Id UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK) {
NSLog(#"bind text error: %s", sqlite3_errmsg(db));
}
} else {
if (sqlite3_bind_null(statement, 1) != SQLITE_OK) {
NSLog(#"bind null error: %s", sqlite3_errmsg(db));
}
}
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(#"DONE");
} else {
NSLog(#"Failed to add contact: %s", sqlite3_errmsg(db));
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}
Most people move that "if database doesn't exist in documents, then copy it from the bundle and open it from there" logic inside a dedicated openDatabase method, but hopefully this illustrates the idea.
I'm creating an app for my school project that has to write data to my sqlite database. It works, as long as the app is running active but as soon as the app closes, my added data is gone and when I want to read this data this will not work off course. I included both my loadData and saveData methods. The two database paths are the same in both functions so it's not that I'm writing my data elsewhere. I really can't find the solution or the problem. I even get the insert success in my output, so the insert is successful.
- (void) saveData:(id)sender{
NSString *sqldb = [[NSBundle mainBundle] pathForResource:#"PXLate" ofType:#"sqlite3"];
sqlite3_stmt *stmt;
NSString *queryInsert = #"INSERT INTO assignments (name, lesson, dueDate, notification, start, at) VALUES ('abc','abc', 'abc', 1, 'abc', 'abc')";
NSLog(#"%#",sqldb);
NSLog(#"%#",queryInsert);
if(sqlite3_open([sqldb UTF8String], &_PXLate) == SQLITE_OK)
{
sqlite3_prepare_v2(_PXLate, [queryInsert UTF8String], -1, &stmt, NULL);
if(sqlite3_step(stmt)==SQLITE_DONE)
{
NSLog(#"insert success");
}
else
{
NSLog(#"insert un success");
NSAssert1(0, #"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(_PXLate));
}
int success=sqlite3_step(stmt);
if (success == SQLITE_ERROR)
{
NSAssert1(0, #"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(_PXLate));
//[_PXLate save:&error];
} sqlite3_finalize(stmt);
}
sqlite3_close(_PXLate);
}
and my loadData function
- (void) loadData:(id)sender
{
//path for database
NSString *sqldb = [[NSBundle mainBundle] pathForResource:#"PXLate" ofType:#"sqlite3"];
//check if present
NSFileManager*fm=[NSFileManager defaultManager];
NSLog(#"path: %#", sqldb);
const char *dbpath = [sqldb UTF8String];
sqlite3_stmt *statement;
if (sqlite3_open(dbpath, &_PXLate) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: #"SELECT * FROM assignments WHERE name='abc'", _label.text];
const char *query_stmt = [querySQL UTF8String];
NSLog(#"name");
NSLog(querySQL);
int response = sqlite3_prepare_v2(_PXLate, query_stmt, -1, &statement, NULL);
NSLog(#"response %d", response);
if (response == SQLITE_OK)
{
NSLog(#"name");
if (sqlite3_step(statement) == SQLITE_ROW)
{
NSString *namefield = [[NSString alloc]
initWithUTF8String:
(const char *) sqlite3_column_text(
statement, 0)];
NSLog(#"name:%#", namefield);
_label.text = namefield;
} else {
_label.text = #"Match not found";
}
sqlite3_finalize(statement);
}
sqlite3_close(_PXLate);
}
}
You have to copy your sqlite to the documents directory and then work with that. Example:
self.databaseName = #"databasename.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
self.databasePath = [[NSString alloc]init];
self.databasePath = [documentsDir stringByAppendingPathComponent:self.databaseName];
[self checkAndCreateDatabase];
And the create method:
-(void)checkAndCreateDatabase
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil];
}
A couple of observations:
As Retterdesdialogs said, you should
Check for existence of database in Documents;
If not there, copy from bundle to Documents; and
Open database from Documents.
You should not open database from bundle, because on the device that folder is read-only.
In your INSERT statement you are not checking the response of sqlite3_prepare_v2, which is a very common source of errors. If this is not SQLITE_OK, you should immediately log sqlite3_errmsg, before you call sqlite3_step.
You are performing sqlite3_step twice in the INSERT statement.
In loadData, you are not logging sqlite3_errmsg if sqlite3_prepare_v2 failed. Always look at sqlite3_errmsg upon any error.
I am trying to insert text data into sqlite3 database in iOS.
I wrote following codes to save data into sqlite3 database.
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"MgDB.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"File Not Found");
}
if((!sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK))
{
NSLog(#"Error in MyInfo");
}
const char *sql = "Insert into MyDB (name,address,email) values('%#','%#','%#')";
sqlite3_bind_text(sqlStmt, 0, [Name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(sqlStmt, 1, [Address UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(sqlStmt, 2, [Email UTF8String], -1, SQLITE_TRANSIENT);
if(sqlite3_prepare(database, sql, -1, &sqlStmt, NULL))
{
NSLog(#"Error in Loading database");
}
if (sqlite3_exec(database, sql, NULL, NULL, NULL) == SQLITE_OK)
{
return sqlite3_last_insert_rowid(database);
}
if(sqlite3_step(sqlStmt) == SQLITE_ROW)
{
NSLog(#"ERROR");
}
}
#catch (NSException *exception)
{
NSLog(#"%#",exception);
}
#finally
{
sqlite3_finalize(sqlStmt);
sqlite3_close(database);
}
according to my above code,I return the last insert ROWID to check that inserted or not.
After saved text data in View,the ROWID have increased.
However when i check my database with FireFox sqlite3 tools, there are no any data that i have inserted.
So i stop running and ReRun my app and add data again.
The last insert ROWID is the same with old count.Not increase even one.
I want to know why it's doesn't save any data into sqlite database.
Is there any problem in my code?
Please help me.
Thanks in advance.
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"MgDB.sqlite"];
You can't write to files included in the application bundle. Create (or copy) the database in the Documents directory instead.
See QA1662.