I'm following some tutorials from youtube for sqlite crud operations. I have textfields with name, contact and address , when i hit save button it show message in console that data is saved but when i look at database it nothing appears there. My database path is correct and no errors in code but 'm confused why it isn't going. My path code is this,
-(void)copyandpaste{
NSArray *arr1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *str1 = [arr1 objectAtIndex:0];
strpath = [str1 stringByAppendingPathComponent:#"personinfo.sqlite"];
if (![[NSFileManager defaultManager]fileExistsAtPath:strpath]) {
NSString *local = [[NSBundle mainBundle]pathForResource:#"personinfo" ofType:#"sqlite"];
[[NSFileManager defaultManager]copyItemAtPath:local toPath:strpath error:nil];
}
NSLog(#"%#",strpath);
}
this method is called in appdelegate.m file,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self copyandpaste];
return YES;
}
I have mad NSObject class for database connection. the connection code is this,
-(id)init{
appdel = (AppDelegate *)[[UIApplication sharedApplication]delegate]; //get all methods in AppDelegate
strmain = appdel.strpath;
return self;
}
-(NSMutableArray *)getalluser:(NSString *)query{
arrdata = [[NSMutableArray alloc]init];
if (sqlite3_open([strmain UTF8String], &(database))==SQLITE_OK) {
sqlite3_stmt *connection;
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &connection, nil)==SQLITE_OK) {
while (sqlite3_step(connection)==SQLITE_ROW) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
NSString *str12 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 0)]; //name in first column
NSLog(#"Checking");
NSString *str13 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 1)]; //contact in second column
NSString *str14 = [[NSString alloc]initWithUTF8String:(char *)sqlite3_column_text(connection, 2)]; //address in third column
[dic setObject:str12 forKey:#"name"];
[dic setObject:str13 forKey:#"contact"];
[dic setObject:str14 forKey:#"address"];
[arrdata addObject:dic];
}
}
sqlite3_finalize(connection);
}
sqlite3_close(database);
return arrdata;
}
My save button code with query is this,
- (IBAction)btnSave:(id)sender {
NSString *saveDATA=[[NSString alloc]initWithFormat:#"insert into stuInfo values('%#','%#','%#')",txtName,txtContact,txtAddress];
dboperations *db = [[dboperations alloc ]init];
BOOL ds = [db getalluser:saveDATA];
if (ds) {
NSLog(#"Data Saved in database");
}else{
NSLog(#"Data is not Saved in database");
}
}
- (NSString*) saveData:(NSString *)name cont:(NSString *)contacts add:(NSString *)address
{
const char *dbpath = [YOUR_DATA_BASE_PATH UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSLog(#"=============saveData open==============");
const char * query="insert into YOUR_TABLE_NAME(name,contacts,address) values(?,?,?);";
sqlite3_stmt *inset_statement;
char *errMsg;
if (sqlite3_open(dbpath, &database)!=SQLITE_OK) {
NSLog(#"Error to Open");
return nil;
}
if (sqlite3_prepare_v2(database, query , -1,&inset_statement, NULL) != SQLITE_OK )
{
NSLog(#"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(database), sqlite3_errcode(database));
NSLog(#"Error to Prepare");
return nil;
}
//No of data to insert
sqlite3_bind_text(inset_statement,1,[name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(inset_statement,2,[contacts UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(inset_statement,3,[address UTF8String], -1, SQLITE_TRANSIENT);
if(sqlite3_step(inset_statement)== SQLITE_DONE)
{
long long lastRowId = sqlite3_last_insert_rowid(database);
NSString *rowId = [NSString stringWithFormat:#"%d", (int)lastRowId];
NSLog(#"Row ID of Last Inserted row %#",rowId);
sqlite3_finalize(inset_statement);
sqlite3_close(database);
NSLog(#"=============saveData Close==============");
return rowId;
}
if (sqlite3_exec(database, query, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
NSLog(#"Failed to Insert msg in message table Error = %s",errMsg);
sqlite3_finalize(inset_statement);
sqlite3_close(database);
NSLog(#"=============saveData Close==============");
return nil;
}
else
{
sqlite3_finalize(inset_statement);
}
}
NSLog(#"=============saveData Close==============");
sqlite3_close(database);
return nil;
}
You are not handling if there are any errors in the SQLite statements you are preparing.
The function will always return true because arrdata is never null
You need to add anelse statements to your
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &connection, nil)==SQLITE_OK)
to show any errors...
NSLog(#"%s",sqlite3_errmsg(database));
Related
This question already has answers here:
sqlite error database is locked
(8 answers)
Closed 6 years ago.
I am getting error Database Locked.
at first attempt it adds the row but after that i am getting the error
database locked.
I am trying to make web page saver so at first time when app loads it is adding the row but when again I try to save any webpage it is not saving and I am getting the error database locked.
Even the deletion is also not happening after saving one web page.
#import "DBManager.h"
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
#implementation DBManager
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
-(BOOL)createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"browser.db"]];
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
NSLog(#"insod");
const char *sql_stmt ="create table if not exists list(sno int primary key,name varchar(50),category varchar(30),path varchar(500),fav int)";
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
}else{
NSLog(#"File Exist");
}
return isSuccess;
}
-(BOOL) Delete:(NSString *) name{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){
NSString *query = [NSString stringWithFormat:#"delete from list where name like '%#'",name];
const char *stmt = [query UTF8String];
sqlite3_prepare_v2(database, stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
NSLog(#"error: %s",sqlite3_errmsg(database));
sqlite3_finalize(statement);
return NO;
}
}else{
sqlite3_close(database);
return NO;
}
}
-(NSDictionary *) CatList:(NSString *) cat{
const char *dbpath = [databasePath UTF8String];
NSDictionary *dict;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL =[NSString stringWithFormat:#"select name,path from list where category like '%#'",cat];
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
// NSLog(#"inside list");
NSMutableArray *arr1 = [[NSMutableArray alloc] init];
NSMutableArray *arr2 = [[NSMutableArray alloc] init];
// NSMutableArray *arr3 = [[NSMutableArray alloc] init];
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[arr1 addObject:name];
//NSLog(#"%#",name);
NSString *category = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
[arr2 addObject:category];
// //NSLog(#"%#",dept);
// NSString *path = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
// [arr3 addObject:path];
}
sqlite3_finalize(statement);
dict = #{#"name":arr1,#"path":arr2};
//NSLog(#"%#",dict);
}else{
NSLog(#"error: %s",sqlite3_errmsg(database));
}
sqlite3_close(database);
}
return dict;
}
- (BOOL) saveData:(NSString*)name category:(NSString*)category path:(NSString*)path{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *highest = #"select max(sno) from list";
const char *Query = [highest UTF8String];
if (sqlite3_prepare_v2(database, Query, -1, &statement, NULL) == SQLITE_OK){
if (sqlite3_step(statement) == SQLITE_ROW){
int sno = sqlite3_column_int(statement, 0);
NSString *insertSQL = [NSString stringWithFormat:#"insert into list values(\"%d\",\"%#\",\"%#\", \"%#\",\"%d\")",sno+1,name, category, path,0];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
sqlite3_finalize(statement);
return NO;
}
}else{
NSString *insertSQL = [NSString stringWithFormat:#"insert into list values(\"%d\",\"%#\",\"%#\", \"%#\",\"%d\")",1,name, category, path,0];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
sqlite3_finalize(statement);
return NO;
}
}
}
sqlite3_close(database);
}
return NO;
}
-(BOOL) Fav:(NSString *) name{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){
NSString *query = [NSString stringWithFormat:#"update list set fav = 1 where name like '%#'",name];
const char *stmt = [query UTF8String];
sqlite3_prepare_v2(database, stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
sqlite3_finalize(statement);
return NO;
}
}else{
return NO;
}
}
-(NSArray *) GetListFav{
const char *dbpath = [databasePath UTF8String];
NSArray *dict;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = #"select name from list where fav = 1";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
NSMutableArray *arr1 = [[NSMutableArray alloc] init];
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)];
[arr1 addObject:name];
}
sqlite3_finalize(statement);
dict = arr1;
}else{
NSLog(#"error: %s",sqlite3_errmsg(database));
}
sqlite3_close(database);
}
return dict;
}
-(BOOL) removeFav:(NSString *) name{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){
NSString *query = [NSString stringWithFormat:#"update list set fav = 0 where name like '%#'",name];
const char *stmt = [query UTF8String];
sqlite3_prepare_v2(database, stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE){
sqlite3_finalize(statement);
return YES;
}else {
sqlite3_finalize(statement);
return NO;
}
}else{
return NO;
}
}
-(NSArray *) GetList{
const char *dbpath = [databasePath UTF8String];
NSArray *dict;
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSString *querySQL = #"select name from list";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
//NSLog(#"inside list");
NSMutableArray *arr1 = [[NSMutableArray alloc] init];
while(sqlite3_step(statement) == SQLITE_ROW)
{
NSString *name = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
[arr1 addObject:name];
}
sqlite3_finalize(statement);
dict = arr1;
}else{
NSLog(#"error: %s",sqlite3_errmsg(database));
}
sqlite3_close(database);
}
return dict;
}
#end
You can only access sqllite once at a time. If you have multiple threads, you can run in this situation. Example:
So always try to close database once it is used using:
sqlite3_close(database);
You need to make sure every sqlite3_open is balanced with a sqlite3_close before trying to do sqlite3_open again:
Your saveData method has quite a few return statements that will prevent the database from ever calling sqlite3_close. Make sure all paths out of the method close the database properly. In the end, this means that you'll try to open the database although it's already open.
Or, better, just open the database once and leave it open, eliminating the repeated opening and closing of the database.
Your Delete, Fav, and removeFav methods are also not closing the database.
A few unrelated observations:
You should be wary about using stringWithFormat to build SQL with string parameters. If the string being searched for had a apostrophe in it, your code will fail. Use ? placeholders and then use sqlite3_bind_text to bind values to those placeholders.
If you make your sno column a AUTOINCREMENT, you won't have to do that "get the max sno before inserting new row" logic. Thus, the CREATE statement might look like:
create table if not exists list (
sno integer primary key autoincrement,
name text,
category text,
path text,
fav integer)
You can then omit sno from the INSERT statements, and it will automatically be assigned a unique identifier.
I have created multiple tables in my database. And now I want insert data into those tables. How to insert multiple tables data can anyone help regarding this.
I have written this code for creating 1 table:
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO ATRG (id, name, language,imgurl) VALUES ( \"%#\",\"%#\",\"%#\",\"%#\")", ID, name, lang,imgUrl];
const char *insert_stmt = [insertSQL UTF8String]; sqlite3_prepare_v2(_globalDataBase, insert_stmt, -1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_DONE)
{
NSLog(#"Record Inserted");
} else { NSLog(#"Failed to Insert Record");
}
Try this I hope it would be helpful!! This is mine code for insert data
#import "Sqlitedatabase.h"
#implementation Sqlitedatabase
+(NSString* )getDatabasePath
{
NSString *docsDir;
NSArray *dirPaths;
sqlite3 *DB;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *databasePath = [docsDir stringByAppendingPathComponent:#"myUser.db"];
NSFileManager *filemgr = [[NSFileManager alloc]init];
if ([filemgr fileExistsAtPath:databasePath]==NO) {
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath,&DB)==SQLITE_OK) {
char *errorMessage;
const char *sql_statement = "CREATE TABLE IF NOT EXISTS users(ID INTEGER PRIMARY KEY AUTOINCREMENT,FIRSTNAME TEXT,LASTNAME TEXT,EMAILID TEXT,PASSWORD TEXT,BIRTHDATE DATE)";
if (sqlite3_exec(DB,sql_statement,NULL,NULL,&errorMessage)!=SQLITE_OK) {
NSLog(#"Failed to create the table");
}
sqlite3_close(DB);
}
else{
NSLog(#"Failded to open/create the table");
}
}
NSLog(#"database path=%#",databasePath);
return databasePath;
}
+(NSString*)encodedString:(const unsigned char *)ch
{
NSString *retStr;
if(ch == nil)
retStr = #"";
else
retStr = [NSString stringWithCString:(char*)ch encoding:NSUTF8StringEncoding];
return retStr;
}
+(BOOL)executeScalarQuery:(NSString*)str{
NSLog(#"executeScalarQuery is called =%#",str);
sqlite3_stmt *statement= nil;
sqlite3 *database;
BOOL fRet = NO;
NSString *strPath = [self getDatabasePath];
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {
if (sqlite3_step(statement) == SQLITE_DONE)
fRet =YES;
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return fRet;
}
+(NSMutableArray *)executeQuery:(NSString*)str{
sqlite3_stmt *statement= nil; // fetch data from table
sqlite3 *database;
NSString *strPath = [self getDatabasePath];
NSMutableArray *allDataArray = [[NSMutableArray alloc] init];
if (sqlite3_open([strPath UTF8String],&database) == SQLITE_OK) {
if (sqlite3_prepare_v2(database, [str UTF8String], -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSInteger i = 0;
NSInteger iColumnCount = sqlite3_column_count(statement);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
while (i< iColumnCount) {
NSString *str = [self encodedString:(const unsigned char*)sqlite3_column_text(statement, (int)i)];
NSString *strFieldName = [self encodedString:(const unsigned char*)sqlite3_column_name(statement, (int)i)];
[dict setObject:str forKey:strFieldName];
i++;
}
[allDataArray addObject:dict];
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return allDataArray;
}
#end
And called that method where you want to use!!
NSString *insertSql = [NSString stringWithFormat:#"INSERT INTO users(firstname,lastname,emailid,password,birthdate) VALUES ('%#','%#','%#','%#','%#')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text];
if ([Sqlitedatabase executeScalarQuery:insertSql]==YES)
{
[self showUIalertWithMessage:#"Registration succesfully created"];
}else{
NSLog(#"Data not inserted successfully");
}
And If you want to fetch data from table then you can do this!!
NSString *insertSql = [NSString stringWithFormat:#"select emailid,password from users where emailid ='%#' and password = '%#'",[_usernameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]],[_passwordTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSMutableArray *data =[Sqlitedatabase executeQuery:insertSql];
NSLog(#"Fetch data from database is=%#",data);
Multiple Execute Query!!
NSString *insertSql = [NSString stringWithFormat:#"INSERT INTO users (firstname,lastname,emailid,password,birthdate) VALUES ('%#','%#','%#','%#','%#')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text];
NSString *insertSql1 = [NSString stringWithFormat:#"INSERT INTO contact (firstname,lastname,emailid,password,birthdate) VALUES ('%#','%#','%#','%#','%#')",_firstNameTextField.text,_lastNameTextField.text,_emailTextField.text,_passwordTextField.text,_BirthdayTextField.text];
NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:insertSql,insertSql1,nil];
for (int i=0; i<array.count; i++)
{
[Sqlitedatabase executeScalarQuery:[array objectAtIndex:i]];
}
See this for your issue:
Insert multiple tables in same database in sqlite
or if you want
Multi-table INSERT using one SQL statement in AIR SQLite
then use this:
http://probertson.com/articles/2009/11/30/multi-table-insert-one-statement-air-sqlite/
I am new in ios, in my product cataloge app I am getting image links from json and after parsing it i am converted it into nsdata and inserting it into sqlite,
problem is that it takes more time than android app for inserting image into database, and i also have a doubt it takes longer than normal time to inserting is there any wrong with my code, please help.
this is the first method to parse images and orther text data
-(void)jsonparseimage:(NSString *)jsonstring
{
NSError *error;
SBJSON *json = [SBJSON new];
NSDictionary *statusDict=[json objectWithString:jsonstring error:&error ];
NSArray *feed= [statusDict objectForKey:#"CATEGORY_DETAILS"];
if([[statusDict objectForKey:#"CATEGORY_DETAILS" ]count ]>0)
{
[appdelegate.categoryarray removeAllObjects];
for (NSDictionary *dictionaryValue in feed)
{
for (NSString *valueKey in [dictionaryValue allKeys])
{
CategoryData *catData=[[CategoryData alloc]init];
catData.categoryname=valueKey;
[appdelegate.categoryarray addObject:valueKey];
NSArray *catInfo =[dictionaryValue objectForKey:valueKey];
NSMutableArray *newArray=[[NSMutableArray alloc]init];
for (NSMutableDictionary *categoryData in catInfo)
{
imageconvert *convert=[[imageconvert alloc]init];
convert.thumbimage=[categoryData objectForKey:#"thumb"];
convert.mainimage=[categoryData objectForKey:#"mainimg"];
convert.categaryname=[categoryData objectForKey:#"cat_nm"];
convert.imageName=[categoryData objectForKey:#"image_nm"];
convert.lastmodified=[categoryData objectForKey:#"lastmodified"];
[newArray addObject:convert];
}
catData.imageArraya=newArray;
NSLog(#"all Dataaaaa :%d %d %#",[catData.imageArraya count],[alldata count],catData.categoryname);
[alldata addObject:catData];
}
}
}
[self.tableView reloadData];
[self insertintoDatabase:alldata];
}
this is second to fetch imagedata in nsdata from link
-(void)insertintoDatabase:(NSMutableArray *)allCatData
{
for (int i=0;i<[allCatData count] ;i++)
{
CategoryData *catData=[allCatData objectAtIndex:i];
appdelegate.categoryString=catData.categoryname;
NSLog(#"array size :%d",[catData.imageArraya count]);
for (int j=0; j<[catData.imageArraya count]; j++)
{
imageconvert *convertedData=[catData.imageArraya objectAtIndex:j];
NSError* error = nil;
NSData* thumbData = [NSData dataWithContentsOfURL: [NSURL URLWithString:[convertedData.thumbimage stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] options:NSDataReadingUncached error:&error];
if (error)
{
NSLog(#"%#", [error localizedDescription]);
}
else
{
[self SaveThumbDatatosql:thumbData WithCatName:catData.categoryname withImagename:convertedData.imageName withLastmodified:convertedData.lastmodified];
}
}
}
[blurView removeFromSuperview];
[self viewDidLoad];
}
this is method for insertion
- (void) SaveThumbDatatosql:(NSData*) thumbData WithCatName:(NSString*) CategoryName withImagename:(NSString*) ImageName withLastmodified:(NSString*) Lastmodified
{
// NSLog(#"thumbData:%# imageData:%# CategoryName:%# ImageName:%# Lastmodified:%#",thumbData,imageData,CategoryName,ImageName,Lastmodified);
sqlite3 *database;
if (sqlite3_open([appdelegate.databasePath UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *statement;
const char* sqliteQuery = "INSERT INTO CategoryTable (ThumbImagePath,Categoryname,Imagename,Lastmodified) VALUES (?,?,?,?)";
if (sqlite3_prepare_v2(database, sqliteQuery, -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_bind_blob(statement, 1, [thumbData bytes], [thumbData length], SQLITE_STATIC);
sqlite3_bind_text(statement, 2, [CategoryName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 3, [ImageName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 4, [Lastmodified UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_step(statement);
sqlite3_finalize(statement);
NSLog(#"inserted ");
}
else
{
NSAssert1(0, #"error:'%s'", sqlite3_errmsg(database));
// NSLog(#"not inserted ");
}
sqlite3_close(database);
}
}
I have setup a GlobalVars class to hold my sqlite3 database variable.
static sqlite3** database;
const char *dbPath;
#implementation GlobalVars : NSObject
+(GlobalVars*)sharedInstance {
static GlobalVars *myInstance = nil;
if(myInstance == nil) {
myInstance = [[[self class] alloc] init];
}
return myInstance;
}
+(sqlite3*)getGlobalDatabase {
return &database;
}
+(void)setGlobalDatabase:(sqlite3*)_database {
database = &_database;
}
Then in the header file I have
static sqlite3** database;
which is above the interface. This is how I setup my database variable.
I am then trying to access it when i open the database and prepare it. I can open it, because the open call returns true. I can not prepare it properly, because the statement returns false and it doesn't go into the if statement. I am wondering if I have messed up my pointers, because the prepare statement isn't working, and it doesn't prepare it properly.
-(void)setAllValues:(NSMutableArray*)array {
if(sqlite3_open([GlobalVars getGlobalDBPath], [GlobalVars getGlobalDatabase]) == SQLITE_OK) {
sqlite3_stmt *insertStatement;
NSString *sqlInsert = [NSString stringWithFormat:#"insert into my_table ('_id', 'name', 'age', 'weight', 'height', 'description') VALUES (%i, '%#', '%i', '%i', '%#', '%#')", ID, name, age, weight, height, description];
//*********** This is not opening, and SQLITE_OK is equal to false ***********
if(sqlite3_prepare_v2(([GlobalVars getGlobalDatabase]), [sqlInsert UTF8String], -1, &insertStatement, nil) == SQLITE_OK) {
if(sqlite3_step(insertStatement) == SQLITE_DONE) {
NSLog(#"insert stepping done");
}
sqlite3_reset(insertStatement);
}
sqlite3_finalize(insertStatement);
sqlite3_close([GlobalVars getGlobalDatabase]);
}
}
The variables for the database are all filled with their correct data, and it seems to open the database without issues. When it comes to preparing, it does not work properly and returns false. Any ideas why. Thank you for your assistance, any help is appreciated.
**
You must try this one ... Maybe its help you :
**
#import "DBManager.h"
#import "userRegistrationClass.h"
static DBManager *sharedInstance = nil;
static sqlite3 *database = nil;
static sqlite3_stmt *statement = nil;
#implementation DBManager
#pragma mark
#pragma mark Get shared Function
+(DBManager*)getSharedInstance{
if (!sharedInstance) {
sharedInstance = [[super allocWithZone:NULL]init];
[sharedInstance createDB];
}
return sharedInstance;
}
#pragma mark
#pragma mark Create DataBase
-(BOOL)createDB{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
// http://www.mycashkit.com/my-earnings.php
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"Dir Path Value is %#",dirPaths);
docsDir = [dirPaths objectAtIndex:0];
NSLog(#"DocsDir Path Value is %#",docsDir);
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"UserRegInfo.sqlite"]];
NSLog(#"Data base Work's %#:",databasePath);
BOOL isSuccess = YES;
NSFileManager *filemgr = [NSFileManager defaultManager];
// NSString *currentPath = [filemgr currentDirectoryPath];
NSLog(#"My file managaer value is %#",filemgr);
//NSLog(#"My current drictory path is %#",currentPath);
//the file will not be there when we load the application for the first time
//so this will create the database table
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
NSLog(#"Constan charcter value is %s:-",dbpath);
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "create table if not exists UserInfo(UserID integer primary key, UserName,Gender,UserEmailID,Password,RePassword,DOB, MobileNo,IsUserType)";
const char *sql_stmt2 = "create table if not exists TestInfo(TestID integer primary key, TestName,TestType)";
// NSString *dbPathFromApp=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"UserRegInfo.sqlite"];[filemgr copyItemAtPath:dbPathFromApp toPath:databasePath error:nil];
NSLog(#"Constan charcter value is %s:-",dbpath);
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) && (sqlite3_exec(database, sql_stmt2, NULL, NULL, &errMsg)!= SQLITE_OK))
{
isSuccess = NO;
NSLog(#"Failed to create table");
}
NSLog(#"Print Sqlite%d",(sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)));
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
}
return isSuccess;
}
#pragma mark
#pragma mark Save Data Function
-(BOOL)saveData:(NSString*)insertSQL{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
NSLog(#" my Sqlite Query is :- %#",insertSQL);
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
}
else
{
NSLog(#"Squlite Error Msg is %s",sqlite3_errmsg(database));
return NO;
}
}
return NO;
}
I have a table in a database which I access like this:
+(NSMutableArray *) queryDatabaseWithSQL:(NSString *)sql params:(NSArray *)params {
sqlite3 *database;
NSMutableArray *rtn = [[NSMutableArray alloc] init];
int index = 0;
NSString *filepath = [self copyDatabaseToDocumentsWithName:#"database"];
if (sqlite3_open([filepath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = [sql cStringUsingEncoding:NSASCIIStringEncoding];
sqlite3_stmt *compiledStatement;
if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
if ([params count]) {
for (int i = 0; i < [params count]; i++) {
NSString *obj = [params objectAtIndex:i];
sqlite3_bind_blob(compiledStatement, i + 1, [obj UTF8String], -1, SQLITE_TRANSIENT);
}
}
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSMutableArray *arr = [[NSMutableArray alloc] init];
index = 0;
const char *s = (char *)sqlite3_column_text(compiledStatement, index);
while (s) {
[arr addObject:[NSString stringWithUTF8String:s]];
index++;
s = (char *)sqlite3_column_text(compiledStatement, index);
}
if (![rtn containsObject:arr]) {
[rtn addObject:arr];
}
}
}
sqlite3_finalize(compiledStatement);
}
NSLog(#"ERROR: %s", sqlite3_errmsg(database));
sqlite3_close(database);
return rtn;
}
This works fine when I call the function like this:
NSLog(#"%#", [database queryDatabaseWithSQL:#"SELECT * FROM FRIENDSUSERS WHERE USER = ?" params:#[[delegate->user objectForKey:#"username"]]]);
Then when I call the function using a string like this it doesn't return any rows:
NSLog(#"%#", [database queryDatabaseWithSQL:#"SELECT * FROM FRIENDSUSERS WHERE USER = ?" params:#[#"username"]]);
I haven't got a clue what is going one with but I have checked the strings match and they do so I'm now stuck
Can anyone see any reason why this would not work
I have run error checks as well and every time it returns no error, or rows :(
Thanks in advance