How To Insert All New Values To The Same Row For Each Session In Sqlite (for Ios)
Solution 1:
A couple of thoughts:
Why do you have two methods to insert the first and last name? Do you need that? Any reason you don't do that in a single SQL statement?
Assuming for a second that you must do it in separate statements like this, the first one should be
INSERTand the second SQL statement should beUPDATE.If you want, SQLite can keep track of the unique identifier for the row for you. So add a column called
user_info_id integer primary key autoincrement. Then, immediately after you insert your data, look at the[database lastInsertRowId], and that will return the value auto-generated for youruser_info_idcolumn.So, going back to prior point, you would insert a row with the first name, immediately retrieve the
lastInsertRowId, and then use that as a parameter to theWHEREclause in yourUPDATEstatement where you set the last name, e.g.,success = [database executeUpdate:@"UPDATE userInfo SET last_name = ? WHERE user_info_id = ?", lastName, @(rowIdValue)];Please note that that value for the
user_info_idis presumably stored in asqlite_int64variable (e.g., the value returned by thelastInsertRowIdmethod), so when you use that in aexecuteUpdatecall, make it aNSNumberby wrapping it with a@(rowIdValue).While FMDB saves you a lot of headaches with binding values to columns and the like, you still should be checking the return values (generally a
BOOLvalue in FMDB). If it failed, log[database lastErrorMessage].Do not open and close the database for each SQL statement. Open the database once and leave it open. It automatically commits the
INSERT/UPDATEstatements as you perform them, so it's very robust.
Solution 2:
If I understood your problem right, you want to create a new entry in your database with every new session. So just give your session an ID (i.e. a random Number) and keep it stored somewhere in your App. If the ID already exists in your Database, chose a new one. If not, insert a new row. Your ID should be the primary key.
So now all values are null, except the ID. If you want to add/change values for this specific ID, just execute something like this:
NSString*sql = [NSString stringWithFormat:@"UPDATE userInfo SET last_name = \"%@\" WHERE id = %@", lastname, uniqueSessionID];
PS: Yes, you should open and close the connection every time you use it, and not keep it open all the time. An open connection takes up resources which could be used somewhere else.
Post a Comment for "How To Insert All New Values To The Same Row For Each Session In Sqlite (for Ios)"