I have a database built in Ruby using SQLite in the following way:
db.execute "CREATE TABLE IF NOT EXISTS Problems(ID INTEGER, stem BLOB NOT NULL, answer BLOB, datetime TEXT, lastmodifiedby TEXT, primary key (ID, datetime) )"
db.execute "INSERT INTO Problems VALUES(1, 'stem', 'answer', '12/26/2012 2:52:18 PM', 'bob')"
db.execute "INSERT INTO Problems VALUES(1, 'stem modified', 'answer', '12/26/2012 2:52:19 PM', 'bob')"
db.execute "INSERT INTO Problems VALUES(1, 'stem modified further', 'answer', '12/26/2012 2:52:20 PM', 'bob')"
The IDs for the first three entries are the same, however the times are different. I am currently using the following code to extract a single entry:
db = SQLite3::Database.new "#{dbname}"
stm = db.prepare "SELECT * FROM Problems WHERE ID=?"
stm.bind_param 1, id
rs = stm.execute
problem = rs.next
My first question – is there a way to condense the last 4 lines of code?
Second, when I select an entry from the Problems database, how would I add an option so that the most recent entry (in this case, the third one) is chosen?
And finally, how do I go about selecting all entries of a certain ID (here I only have the int 1, but in reality there are many others) so that I can output them as a string / write to a file, etc.
I have found answers to questions regarding most recent entry selection, but they seem quite complex. Would an ORDER BY work in some way?
Thanks for the help.
First of all, I think you have a data format problem. I don’t think SQLite will understand
'12/26/2012 2:52:18 PM'as a timestamp so you’ll end up comparing your timestamps as strings. For example, if I add'12/26/2012 2:52:20 AM'to the mix, I get'12/26/2012 2:52:18 PM'and'12/26/2012 2:52:20 PM'as the lowest and highest values and that only makes sense if they’re being compared as strings. Switch your data to ISO 8601 format so that you have these:and things will sort properly.
Once you have that fixed, you can use ORDER BY and LIMIT to peel off just one record: