Reputation: 1580
HI Iam using SQLite db in iOS.I have created DB successfully and table also. But when i tried to save textfield contents into database but it showing "failed to add contact "alert.
I have doubt in my INSERT string and the way i assign textfield values in it.
can anyone please help me to solve this?
- (IBAction)save:(id)sender {
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &myDatabase) == SQLITE_OK) {
NSString *insertSQL = [NSString stringWithFormat:
@"INSERT INTO LubnaNewUser (name,address,phonenumber,tier) VALUES (\"%@%@%@%@\")",
name.text,address.text,phonenumber.text,tier.text];
const char*insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(myDatabase, insert_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
statusOfAddingToDB = [NSString stringWithFormat:@"Text added -- %@", name.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);
}
}
new code
if (sqlite3_open(dbpath, &myDatabase) == SQLITE_OK)
{
//Select all from SAMPLETABLE. This includes the 'id' column and 'message' column.
NSString *querySQL = @"SELECT * FROM LubnaNewUser";
const char *query_stmt = [querySQL UTF8String];
if (sqlite3_prepare_v2(myDatabase, query_stmt, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *text = [[NSString alloc]
initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)]; //Num 1 means on what column. Column 0 = 'id' column while Column 1 = 'message' column in our query result.
[list addObject:text];
//NSLog(@"count: %d", [list count]);
}
sqlite3_finalize(statement);
}
sqlite3_close(myDatabase);
}
Upvotes: 0
Views: 84
Reputation: 180270
Call sqlite3_errmsg to get an error message.
Anyway, you have to write four values into the VALUES clause:
NSString *insertSQL = [NSString stringWithFormat:
@"INSERT INTO LubnaNewUser (name,address,phonenumber,tier) VALUES ('%@','%@','%@','%@')",
name.text,address.text,phonenumber.text,tier.text];
However, this will blow up when any of these strings contains a quote. Better use parameters:
const char *insertSQL = "INSERT INTO LubnaNewUser (name,address,phonenumber,tier) VALUES (?,?,?,?)";
sqlite3_prepare_v2(myDatabase, insertSQL, -1, &statement, NULL);
sqlite3_bind_text(statement, 1, [name.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 1, [address.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 1, [phonenumber.text UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(statement, 1, [tier.text UTF8String], -1, SQLITE_TRANSIENT);
...
Upvotes: 1