· 7 years ago · Nov 24, 2018, 01:02 PM
1require 'mysql'
2
3class Mysql
4 class Stmt; include Enumerable; end
5 class Result; include Enumerable; end
6end
7
8Mysql.init
9conn = Mysql.real_connect('localhost', 'root', nil, 'test')
10
11conn.query 'drop table if exists topics'
12conn.query <<-eosql
13CREATE TABLE `topics` (
14 `id` int(11) NOT NULL AUTO_INCREMENT,
15 PRIMARY KEY(id),
16 `name` varchar(255) DEFAULT NULL,
17 `created_at` datetime NOT NULL)
18eosql
19
20conn.query "INSERT INTO topics (name, created_at) VALUES ('omg', NOW())"
21conn.query "INSERT INTO topics (name, created_at) VALUES ('omg', NOW())"
22
23# prepared statements return real data structures for dates, eliminating the
24# need for string parsing when dealing with dates. Other values like ints,
25# and floats are automatically cast:
26stmt = conn.prepare("SELECT id, created_at FROM topics LIMIT 1")
27stmt.execute
28id, date = stmt.first
29
30puts "### WITH STATEMENTS"
31p :date => [date.year, date.month, date.day, date.hour, date.minute, date.second, date.second_part]
32p :id => [id, id.class]
33stmt.close
34
35# Compare with traditional query:
36puts "### WITHOUT STATEMENTS"
37id, date = conn.query("SELECT id, created_at FROM topics LIMIT 1").first
38p :date => date
39p :id => [id, id.class]
40
41puts