-
-
Save anonymous/6e93f2973f4c6b79c86c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'sqlite3' | |
require 'time' # This is needed for DateTime | |
begin | |
db = SQLite3::Database.open "eggs.db" | |
stm = db.prepare "SELECT ID,TimeStamp FROM Eggs" | |
rs = stm.execute # Get the data to work with. | |
ts = "" | |
id = 0 | |
stm2 = db.prepare "UPDATE Eggs SET TimeStamp = ? WHERE ID = ?" | |
stm2.bind_param 1, ts # Really, bind_param does not replace the ?'s until you execute it. So | |
stm2.bind_param 2, id # you can bind a param, then execute, then change the variable's value, and execute again. and repeat! | |
while row = rs.next | |
id = row[0].to_i # So here... | |
ts = Time.parse(DateTime.strptime(row[1] + " CDT", "%F %T %Z").to_s).utc.iso8601 # ...and here, we update the variables... | |
puts "Updating timestamp on row #{id} to #{ts}" | |
stm2.execute # ..and execute again! And the new values are used! | |
end | |
# This rescue line should ALWAYS read rescue Exception, not rescue SQLiteException or whatever. | |
# Because if it just rescues SQLite exceptions, an error in the code WILL NOT BE REPORTED, which is a BAD THING. | |
rescue Exception => e | |
puts "Exception occurred" | |
puts e | |
ensure | |
# READ THIS!! READ THIS!! | |
# I just discovered that it is optional to use the 'ensure' block for closing the database; | |
# Ruby SQLite3 will close the database on its own (via an 'ensure', too!) | |
# | |
# Also, if you use the 'ensure' yourself, and you close the db, you MUST ALSO CLOSE ANY STATEMENTS that you used throughout the program. | |
# Whereas if you don't use the ensure, Ruby's SQLite code will once again auto-close them. So I will probably be leaving out the | |
# ensure in my own code in the future. | |
stm.close if stm | |
stm2.close if stm2 | |
db.close if db | |
end | |
# Please email/wm me any question you might have about this code or the comments herein. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment