Data insertion problem in sqlite - iphone

I am inserted first record in sqlite, and when i am trying to add another it shows "Database Locked" error.
the code is:
- (void) addRecord:(NSMutableDictionary *)recordDict
{
if(addStmt == nil) {
const char *sql = "insert into Product(ProID, BarCode , ProductName ) Values(?,?,?)";
if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, #"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
NSInteger recordId = [[recordDict objectForKey:#"ProID"] intValue];
NSLog(#"%d",recordId);
sqlite3_bind_int(addStmt, 1,recordId);
sqlite3_bind_text(addStmt, 2, [[recordDict objectForKey:#"BarCode"] UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(addStmt, 3, [[recordDict objectForKey:#"ProductName"] UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, #"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
{//SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
rowID = sqlite3_last_insert_rowid(database);
NSLog(#"last inserted rowId = %d",rowID);
//Reset the add statement.
sqlite3_reset(addStmt);
}
}

Nothing in your code jumps out at me. If you are getting "Database Locked" then that means you have an open transaction that is locking the database. This could be in your app (in another thread perhaps) or in another app that is also accessing the same database.

"Database Locked" means the database is not writable, two reasons for this -
1) You forget to finlalize your previous compiled statement or forgot to close the database try this in your previous query -
sqlite3_finalize(compiledStatement);
sqlite3_close(database);
2) Are you copying the database in Documents directory before using it? You can't modify the database in bundle itself. Here is the code to copy the database in documents directory.
-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything
if(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 *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
Here is how to get database path -
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [[documentsDir stringByAppendingPathComponent:databaseName] retain];
NSLog(#"%#",databasePath);

Related

LocalStorage or SQLite ?

I'm working on my app that let me to store my online DVD's information on my iphone. Just wonder to use localStorage or SQLite. Also I'm gonna update my app in the future and I dont want to loose my stored data. Which one do you suggest me ?!
Cheers
my online DVD's information
can be large information, then use core data or SQLite.
Also I'm gonna update my app in the future and I dont want to loose my
stored data
if you update without deleting the old version, SQLite data remains. This works same for NSUserDefault too. You can use Keychains for permanant data storage, but for small amount of data. Can't say more without knowing more about your requirement.
I do not know much about localStograge anyway SQLite will give you good options:
Portable to Android
Can be updated without losing your previous database.
here is a sample code to init DB and upgrade it.
+(void) InitalizeDB
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"QuestionsDB.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
if (success)
{
if (sqlite3_open([dbPath UTF8String], &gDatabase) != SQLITE_OK)
{
sqlite3_close(gDatabase);
gDatabase = nil;
}
}
if (gDatabase != nil)
[self Upgrade];
}
+(void)Upgrade
{
sqlite3 *NewDatabase = nil;
NSString *NewDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"QuestionsDB.sqlite"];
const char *szVersion = "SELECT DBVersion FROM Version";
sqlite3_stmt *sqlOldVersion;
sqlite3_stmt *sqlNewVersion;
if (sqlite3_open([NewDBPath UTF8String], &NewDatabase) != SQLITE_OK)
{
sqlite3_close(NewDatabase);
NewDatabase = nil;
}
if (NewDatabase != nil)
{
if (sqlite3_prepare_v2(gDatabase, szVersion, -1, &sqlOldVersion, NULL) != SQLITE_OK)
NSAssert1(0, #"Failed to compile sql statment %s", sqlite3_errmsg(gDatabase));
if (sqlite3_prepare_v2(NewDatabase, szVersion, -1, &sqlNewVersion, NULL) != SQLITE_OK)
NSAssert1(0, #"Failed to compile sql statment %s", sqlite3_errmsg(NewDatabase));
if (sqlite3_step(sqlOldVersion) == SQLITE_ROW && sqlite3_step(sqlNewVersion) == SQLITE_ROW)
{
if (sqlite3_column_int(sqlOldVersion, 0) < sqlite3_column_int(sqlNewVersion, 0))
{
[self UpgradeCategories:NewDatabase];
[self UpgradeQuestions:NewDatabase];
[self UpgradeQuestionChoices:NewDatabase];
}
}
else
{
NSAssert(0, #"Failed to retreive questions database version.");
}
}
sqlite3_close(NewDatabase);
}

How to insert only one username and password in SQLite database?

I have an application where I have two textfields and a button. In the first textfield I am entering the username of the user and in the second textfield I am entering the password of the user. When the user enters the username and password and click on create user button a backend api is called which will register the username and password of the user and at the time I want to enter the username and password of the user in local SQLite databse in encrypted format.
When a user is registered the username of that particular user should get displayed in the first textfield and it should not be editable and password field should be editable. Only one user is allowed to be registered for the entire application.
Don't use a sqlite dbs to store user credentials. With reverse engineering it is fairly simple to get to the data. This because you probably have some value in your program you use to encrypt/decrypt the password. For security purposes, please use the keychain. There are several projects on github which makes it very easy to use the keychain. There is no more secure way for saving credentials then the keychain, so please use that to store your credentials!!!
If I understood your requirement correctly, You can follow the below guideline.
Before inserting the data to the table, You can check if any record is added to the table.
If the count is 0, you can proceed to insert the record, else you can prompt the error.
I think this will be the simplest way to do this.
First step is to check the database exist in resource folder and create database:-
1)
-(void)checkAndCreateDatabase{
databaseName = #"databasename.sql";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
BOOL success;
// Create a FileManager object, we will use this to check the status of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything
if(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 *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
2) call the function to retrieve the data:-
-(NSMutableArray *) readFromDatabase:(NSString *)query{
// Setup the database object
sqlite3 *database;
// Init the animals Array
returnArray = [[NSMutableArray alloc] init];
NSString *readCommand= query;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = [readCommand UTF8String];
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) {
// Read the data from the result row
[returnArray addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]];
[returnArray addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
return returnArray;
}
3) check for the retrun array is empty or nil then call the insert function defined at step
4) Insert into the database
-(void)insertIntoDatabase:(NSString *)username:(NSString *)password{
// Setup the database object
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
NSString *insertCommand=#"Insert into tableName values(username,password)";
const char *sqlStatement = [insertCommand UTF8String];
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) {}
sqlite3_finalize(compiledStatement);
}
// Release the compiled statement from memory
}
sqlite3_close(database);
}
You can use NSUserDefaults saving locally it. following code is for saving data.
perf = [NSUserDefaults standardUserDefaults];
[perf setObject:#"1" forKey:#"remember"];
[perf setObject:emailAddresTextField.text forKey:#"email"];
[perf setObject:passwordTextField.text forKey:#"password"];
[perf synchronize];
And for retrieving data use following code
perf=[NSUserDefaults standardUserDefaults];
NSString *remString = [perf stringForKey:#"remember"];
if ([remString isEqualToString:#"1"]) {
emailAddresTextField.text=[perf stringForKey:#"email"];
passwordTextField.text = [perf stringForKey:#"password"];
[rememberBtn setTag:1];
[rememberBtn setImage:[UIImage imageNamed:#"on_radioButton.png"] forState:0];
}

Inserting array of value in Sqlite3 i-phone

I am trying to insert a set of values in an sqlite table using a for loop. It is inserting only one set of value. I am posting here my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:#"myDatabase.sql"];
for(int i=0;i<[arr count];i++)
{
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
NSLog(#"\n inserting data \n");
sqlite3_exec(database, [[NSString stringWithFormat:#"INSERT INTO AnswerConnect VALUES('%#')",[arr objectAtindex:i] ] UTF8String], NULL, NULL, NULL);
//sqlite3_finalize(compiledStatement);
sqlite3_close(database);
}
}
Thanks in advance.
You have to first prepare a sqlite statement to insert data in table.Try this :
sqlite3_stmt *statement = nil
const char *sql = "insert into tablename (col1,col2) Values( ?, ?)";
if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK)
{
NSLog(#"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}
for(int i=0;i<[arr count];i++)
{
sqlite3_bind_text(statement, 1,[[arr objectAtindex:i] UTF8String] , -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(add_statement))
{
NSLog(#"Error while inserting result data. '%s'", sqlite3_errmsg(database));
}
//Reset the add statement.
sqlite3_reset(statement);
}
Don't do like that! Don't open/close SQLite connection in loop like that! Open handle to database outside from loop and than just use pointer on it. In this kind of request it's unsafe to insert format, because SQL statement may be compiled with some kind of injection code. Use sqlite3_stmt instead and bind values to it. Also if you compile only one instance of sqlite3_stmt and reuse it, this will give you better performance than compiling new statements all the time.
How many columns in each data set? Does it insert only one value from single data set like string?

Not able to insert data in to sqlite table

I am new to iphone development,i was trying to insert the data in a sqlite table .but data is not inserted in the table.there was no error on the console.
NSString *string1=#"Test";
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"TestData" ofType:#"sqlite"];
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *compiledStatement=nil;
char * sql = "insert into Test (title,summary,question,choice,answer) values (?,?,?,?,?)";
if (sqlite3_prepare_v2(database, sql, -1, &compiledStatement, NULL) == SQLITE_OK)
{
{
sqlite3_bind_text(compiledStatement, 1, [string1 UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 2,[string1 UTF8String] , -1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 3, [string1 UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 4, [string1 UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(compiledStatement, 5, [string1 UTF8String], -1,SQLITE_TRANSIENT);
if(sqlite3_step(compiledStatement) != SQLITE_DONE )
{
NSLog( #"Error: %s", sqlite3_errmsg(database) );
}
else {
NSLog( #"Insert into row id = %d", sqlite3_last_insert_rowid(database));
}
}
As your database in resource bundle you are trying to modify and update it. The better approach would be place your database first time in documents directory of sandbox and then perform operation on that database.
Here is the method using which you can move your database to documents directory of your application's sandbox. This method should be called only once while using database operation.(because only first time we need to place it at that location, other times we just need to access it).
Code :
// Name : configureDatabase:
// Description : Method configures the database with new name.
// Arguements : NSString : Databse file name
// Retrun : None
-(void) configureDatabase:(NSString *)newDatabaseName
{
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [[documentsDir stringByAppendingPathComponent:newDatabaseName]retain];
// Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase:databasePath];
}
// Name : checkAndCreateDatabase:
// Description : Method checks and creates the database file at the given path if its not present.
// Arguements : NSString : file path.
// Retrun : None.
-(void) checkAndCreateDatabase:(NSString *)dbPath
{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:dbPath];
// If the database already exists then return without doing anything
if(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 *databasePathFromApp=[[NSBundle mainBundle] pathForResource:#"TestData" ofType:#"sqlite"];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:dbPath error:nil];
}
Also note that if we are using database so it is good practice to locate it first in some directory from where user can take backup. Documents directory of sandbox is one of these backup ready directory.
Thanks,

SQLite iPhone - Insert Fails

I am trying to insert a value to a SQLite db, but everytime I try my program simply crashes with no error message at all.
Here is my code:
- (void) insertToDatabase:(NSString *) refName {
// The Database is stoed in the application bundle
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"staticdata.sqlite"];
if(sqlite3_open([path UTF8String], &database) == SQLITE_OK){
const char *sql = "Insert into usersDates(dateDescription) VALUES (?)";
sqlite3_stmt *init_statement;
sqlite3_bind_text(init_statement, 1, [refName UTF8String], -1, SQLITE_TRANSIENT);
if(!sqlite3_prepare_v2(database, sql, -1, &init_statement, NULL) == SQLITE_OK){
NSAssert1(0, #"Failed to insert to database file with message '%s'.", sqlite3_errmsg(database));
}
if(sqlite3_step(init_statement) != SQLITE_DONE ) {
NSLog( #"Error: %s", sqlite3_errmsg(database) );
} else {
NSLog( #"Insert into row id = %d", sqlite3_last_insert_rowid(database));
}
sqlite3_finalize(init_statement);
} else {
sqlite3_close(database);
NSAssert1(0, #"Failed to open database file with message '%s'.", sqlite3_errmsg(database));
}
}
The error seems to occur on the bind statement. I have confirmed the database is actually being opened, and refname is correctly being passed to my method.
Can anyone help? I would normally use core data, however this is a bug fix to an existing project, and I simply do not have the time to allocate to making the move to core data.
The order of your statements is incorrect. bind_() is used after prepare()
SQLite bind() documentation
The first argument to the sqlite3_bind_*() routines is always a pointer to the sqlite3_stmt object returned from sqlite3_prepare_v2() or its variants.
const char *sql = "Insert into usersDates(dateDescription) VALUES (?)";
sqlite3_stmt *init_statement;
if(!sqlite3_prepare_v2(database, sql, -1, &init_statement, NULL) == SQLITE_OK){
NSAssert1(0, #"Failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}
sqlite3_bind_text(init_statement, 1, [refName UTF8String], -1, SQLITE_TRANSIENT);
sqlite_step(init_statement);