Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am calling this function and removes all the data first and then insert the updated values in it. but some how all the tables are removed from database.it always shows the alertview from the code.not sure what i am dong wrong.any help will be appereciated. Thank you..
-(void)fillDate
{
filemgr=[NSFileManager defaultManager];
NSString *querySQL = #"delete from getdate";
const char *dbpath = [[appDelegate getDBPath] UTF8String];
//NSLog(#"path= %#",dbpath);
BOOL flag=FALSE;
if (sqlite3_open(dbpath, &dtdb) == SQLITE_OK)
{
//"open";
const char *query_stmt = [querySQL UTF8String];
sqlite3_prepare_v2(dtdb,query_stmt,-1,&statement,NULL);
if (sqlite3_step(statement)==SQLITE_DONE)
{
//table deleted
flag=TRUE;
}
else
{
UIAlertView *d=[[UIAlertView alloc]initWithTitle:#"Message" message:#"Your Table does not deleted" delegate:self cancelButtonTitle:#"ok" otherButtonTitles: nil];
[d show];
flag=FALSE;
}
}
else
{
//"can't open";
}
sqlite3_close(dtdb);
sqlite3_finalize(statement);
if (flag)
{
sqlite3_stmt *stmt;
const char *cdbpath=[[appDelegate getDBPath] UTF8String];
if ((sqlite3_open(cdbpath,&dtdb)==SQLITE_OK))
{
char* errorMessage;
sqlite3_exec(dtdb, "BEGIN TRANSACTION", NULL, NULL, &errorMessage);
char buffer[] = "INSERT INTO getdate(lastdate) VALUES (?1)";
sqlite3_prepare_v2(dtdb, buffer, strlen(buffer), &stmt, NULL);
// for (unsigned i = 0; i < 1; i++)
// {
// NSMutableDictionary *dict=[arrayAllEvents objectAtIndex:i];
//NSLog(#"dict:%#",dict);
sqlite3_bind_text(stmt, 1, [[df stringFromDate:[NSDate date]]UTF8String], -1, SQLITE_STATIC);
int success = sqlite3_step(stmt);
sqlite3_reset(stmt);
if (success != SQLITE_DONE)
{
//nslog(#"error: %s",sqlite3_errmsg(dtdb));
}
//nslog(#"... data created.");
// }///for
if(sqlite3_exec(dtdb, "COMMIT TRANSACTION", NULL, NULL, &errorMessage)==SQLITE_OK)
{
NSLog(#"commited Events");
}
else
{
NSLog(#"Not commited");
}
// sqlite3_exec(dtdb, "COMMIT TRANSACTION", NULL, NULL, &errorMessage);
sqlite3_finalize(stmt);
}//
}
sqlite3_close(dtdb);
}
if you have updated your database then just replace the new database with old one.delete the app and run again. your code seem to be perfect.
Related
I have some values in labels and i'm trying to store it in my database but when i hit save button it isn't save and log a message failed to save. The database is properly made but data is not storing. My code for saving data is this,
- (IBAction)btnSave:(id)sender {
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO data (ID, ALERT, XREF,TEXT,GRAPHIC,PROMPT,VOICE) VALUES (\"%#\", \"%#\", \"%#\",\"%#\",\"%#\",\"%#\",\"%#\")", _lblID.text, _lblAlert.text, _lblxref.text,_lbltext.text, _lblgraphic.text, _lblprompt.text,_lblvoice.text];
NSLog(#"DDD %#",insertSQL);
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
_lblstatus.text = #"Contact added";
} else {
_lblstatus.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
if (sqlite3_step(statement) == SQLITE_DONE){
_lblstatus.text = #"Contact added";
} else {
NSLog(#"prepare failed: %s", sqlite3_errmsg(contactDB));
_lblstatus.text = #"Failed to add contact";
}
1. Replace this snippet in your code to print error message. It will help you to find exact issue.
2. May be the SQL query which your forming is syntactically wrong.
I am trying to insert a BLOB data of SignatureView using this code but when i actually browse the database there is null instead of data.
My signature table schema is given below.
create table sign(id integer primary key AUTOINCREMENT, image blob,invoiceid integer);
-(void)storeImageData:(NSData *)imageData withInvoiceID:(NSInteger)invoiceID{
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"database.sqlite3"];
const char *dbpath = [dbPath UTF8String];
sqlite3 *contactDB;
sqlite3_stmt *statement;
NSLog(#"%#",dbPath);
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
int invoiceIDINT = (int)invoiceID;
//
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO sign (image,invoiceid) VALUES (?,%d)", invoiceIDINT];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
sqlite3_bind_blob(statement, 2, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
sqlite3_step(statement);
} else {
const char *Error = sqlite3_errmsg(database);
NSString *error = [[NSString alloc]initWithUTF8String:Error];
UIAlertView *view = [[UIAlertView alloc]initWithTitle:#"Error2" message:[NSString stringWithFormat:#"Last inserted ID: %#",error] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[view show];
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
Always check the result of sqlite3_prepare_v2. If it fails, log the problem using sqlite3_errmsg.
Only call sqlite3_finalize if sqlite3_prepare_v2 succeeds.
You get NULL for the blob because your call to sqlite3_bind_blob is passing the wrong column index. It should be 1, not 2 since your want to bind to the first ? in your INSERT statement.
Why the inconsistency? Why do you use stringWithFormat to set the value for the invoiceid column and then use sqlite_bind_xxx for the image column? You should bind both. Never use stringWithFormat to build a query.
You call sqlite3_step twice. Only call it once and bind your values before you call it.
You appear to be writing to a database inside your app's resource bundle. You can't do that on a real device. It works in the simulator but not on real iOS devices. You need to put your database file in the Documents folder.
Given all of the above, your code should be something like this:
-(void)storeImageData:(NSData *)imageData withInvoiceID:(NSInteger)invoiceID{
// This is wrong - you need to update this to use the Documents folder
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"database.sqlite3"];
const char *dbpath = [dbPath UTF8String];
NSLog(#"%#",dbPath);
sqlite3 *contactDB;
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
const char *insert_stmt = "INSERT INTO sign (image, invoiceid) VALUES (?, ?)";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(contactDB, insert_stmt, -1, &statement, NULL) == SQLITE_OK) {
sqlite3_bind_blob(statement, 1, [imageData bytes], [imageData length], SQLITE_TRANSIENT);
sqlite3_bind_int(statement, 2, (int)invoiceID);
if (sqlite3_step(statement) == SQLITE_DONE) {
// Row inserted successfully
} else {
const char *Error = sqlite3_errmsg(contactDB);
NSString *error = [[NSString alloc] initWithUTF8String:Error];
UIAlertView *view = [[UIAlertView alloc] initWithTitle:#"Error2" message:[NSString stringWithFormat:#"Last inserted ID: %#",error] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[view show];
}
sqlite3_finalize(statement);
} else {
NSLog(#"Unable to prepare statement %s: %s", insert_stmt, sqlite3_errmsg(contactDB));
}
sqlite3_close(contactDB);
} else {
NSLog(#"Unable to open database at path %#: %s", dbPath, sqlite3_errmsg(contactDB));
}
}
Hey my code is very simple , i have crated a sqlite table with one column id and message.
my sqlite table is created successfully. i want to insert 5 string value in message column .my code for insert string value
- (IBAction)addTextToDatabase:(id)sender
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &myDatabase) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO SAMPLETABLE (MESSAGE) VALUES (\"%#\")",
self.textField.text];
const char *insert_stmt = [insertSQL UTF8String];
for (int k = 0; k < 5; k++) {
sqlite3_prepare_v2(myDatabase, insert_stmt,
-1, &statement, NULL);
sqlite3_finalize(statement);
}
// sqlite3_prepare_v2(myDatabase, insert_stmt,
// -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
statusOfAddingToDB = [NSString stringWithFormat:#"Text added -- %#",
textField.text];
} else {
statusOfAddingToDB = #"Failed to add contact";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"DB Status"
message:statusOfAddingToDB delegate:nil cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
// sqlite3_finalize(statement);
sqlite3_close(myDatabase);
}
}
but when i check my database only one value is added to it.please help how to achieve this?
Write sqlite3_step statement within for loop before sqlite3_finalize statement
You have to run this statement:
sqlite3_step(compiledStatement) == SQLITE_DONE
after each insertion.
This question already has an answer here:
When I try SQLite on iOS, INSERT and UPDATE does not work
(1 answer)
Closed 9 years ago.
This is code I'm using to insert data into table,
sqlite3 *database;
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"mobdb.sqlite"];
if(sqlite3_open([dbPath UTF8String],&database)==SQLITE_OK)
{
const char *sqlstatement = "INSERT INTO mobDetails (nMonId, nScore) VALUES (?,?)";
sqlite3_stmt *compiledstatement;
if(sqlite3_prepare_v2(database,sqlstatement , -1, &compiledstatement, NULL)==SQLITE_OK)
{
NSString * str1 =#"1";
NSString * str2 =#"12";
sqlite3_bind_int(compiledstatement, 1, [str1 integerValue]);
sqlite3_bind_int(compiledstatement, 2, [str2 integerValue]);
if(sqlite3_step(compiledstatement)==SQLITE_DONE)
{
NSLog(#"done");
}
else
{
NSLog(#"ERROR");
}
sqlite3_reset(compiledstatement);
}
else
{
NSAssert1(0, #"Error . '%s'", sqlite3_errmsg(database));
}
sqlite3_close(database);
}
Its shows "done" message but data not inserted into the table can any one help me for this.
also how to insert string in the table ?
The problem is that the app bundle is read-only (as you could have probably found out after 5 minutes of googling). Consequently, you can't insert to a database in the app bundle.
One thing that is wrong with the usage of the SQLite API is that you are calling sqlite3_reset() whereas sqlite3_finalize() should have been called. (Thanks #trojanfoe.)
(Oh, and this has absolutely nothing to do with Xcode at all.)
- (void) saveData
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:
#"INSERT INTO CONTACTS
(name, address, phone) VALUES (\"%#\", \"%#\", \"%#\")",
name.text, address.text, phone.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB, insert_stmt,
-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
status.text = #"Contact added";
name.text = #"";
address.text = #"";
phone.text = #"";
} else {
status.text = #"Failed to add contact";
}
sqlite3_finalize(statement);
sqlite3_close(contactDB);
}
}
What am i doing wrong here?? i have three table in database, and i need to delete all data from them.
-(void)deleteAllDataFromTables
{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSLog(#"%#", appDelegate.databasePath);
int result = sqlite3_open([appDelegate.databasePath UTF8String], &db);
if(result == SQLITE_OK)
{
NSLog(#"deleteCalled");
const char *deleteData = "delete from CustomerNumberTable";
int outcome = sqlite3_prepare_v2(db, deleteData, -1, &statement, NULL);
if(outcome == SQLITE_OK)
{
int res = sqlite3_step(statement);
if(res == SQLITE_DONE)
{
NSLog(#"deleted from Customer Table");
}
else
{
NSLog(#"not able to execute step statement");
}
}
else
{
NSLog(#"not deleted from Customer Table");
NSLog(#"the error is %s", sqlite3_errmsg(db));
}
sqlite3_finalize(statement);
const char *deleteData2 = "delete from KeyCodeTable";
int outcome2 = sqlite3_prepare_v2(db, deleteData2, -1, &statement, NULL);
if(outcome2 == SQLITE_OK)
{
int res = sqlite3_step(statement);
if(res == SQLITE_DONE)
{
NSLog(#"deleted from KeyCodeTable");
}
else
{
NSLog(#"not able to execute step statement");
}
}
else
{
NSLog(#"not deleted from KeyCodeTable");
NSLog(#"the error is %s", sqlite3_errmsg(db));
}
sqlite3_finalize(statement);
const char *deleteData3 = "delete from SRNumberTable";
int outcome3 = sqlite3_prepare_v2(db, deleteData3, -1, &statement, NULL);
if(outcome3 == SQLITE_OK)
{
int res = sqlite3_step(statement);
if(res == SQLITE_DONE)
{
NSLog(#"deleted from SRNumberTable");
}
else
{
NSLog(#"not able to execute step statement");
}
}
else
{
NSLog(#"not deleted from SRNumberTable");
NSLog(#"the error is %s", sqlite3_errmsg(db));
}
sqlite3_finalize(statement);
}
else
{
NSLog(#"Not able to open database for deleting");
}
}
On console, i am getting
Application[54974:a0b] deleteCalled
2014-01-03 16:12:55.442 Application[54974:a0b] deleted from Customer Table
2014-01-03 16:12:55.443 Application[54974:a0b] deleted from KeyCodeTable
2014-01-03 16:12:55.445 Application[54974:a0b] deleted from SRNumberTable
But when i am opening the database in on mac, the data is intact there..!! What is wrong with my code?? why isn't the data getting deleted??
I think you are copying your database from bundle to documents directory. So, the updated database will be present in documents directory. You seems to look the database from your workspace which is never going to be of updated one.
Your code opens database with sqlite3_open(), but does not close it using sqlite3_close(). This means that your database is probably still in open transaction, and quite possibly has 2 files: one is main database.db, and journal file database.db-journal which contains uncommitted intent to delete your tables.
You should make sure that your application closes database before you copy database file from the device to the host. At the very least, copy both main database AND journal file as one set. It is still likely to have consistency issues, but you should see your changes.
Try instead of sqlite3_prepare_v2 to sqlite3_exec. This working fine for me.
Just Ref:
char *errMsg;
const char *dbPath = [databasePath UTF8String];
if (sqlite3_open(dbPath, &database) == SQLITE_OK) {
NSLog(#"Db OPened ");
NSString *queryLists = [NSString stringWithFormat:#"delete from Table_name"];
const char *query_stmt = [queryLists UTF8String];
if (sqlite3_exec(database, query_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK){
NSLog(#"Error %s", errMsg);
NSLog(#"Table Not Deleted");
}
}
1st thing Don't write same functionality code repeatedly in place create one function that delete all data from given table name,
2nd make sure you are looking at correct sqlite file in mac.
look this,
-(void)deleteAllData
{
[self deleteTable: CustomerNumberTable];
[self deleteTable: SRNumberTable];
[self deleteTable: KeyCodeTable];
}
-(void)deleteTable:(NSString *)table;
{
const char *dbpath=[appDelegate.databasePath UTF8String];
if (sqlite3_open(dbpath, &dtdb)==SQLITE_OK)
{
sqlite3_stmt *stmt;
const char *qry=[[NSString stringWithFormat:#"delete from %#",table] UTF8String];
sqlite3_prepare_v2(dtdb, qry, -1, &stmt, NULL);
if (sqlite3_step(stmt)==SQLITE_DONE)
{
NSLog(#"%# Table data deleted",table);
}
sqlite3_finalize(stmt);
sqlite3_close(dtdb);
}
}