-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite_example.rb
81 lines (70 loc) · 1.46 KB
/
sqlite_example.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
require "sqlite3"
# db connection and configurations
$db = SQLite3::Database.new "test.db"
$db.results_as_hash = true
# helper methods
def disconnect_and_quit
$db.close
puts "Bye!"
exit
end
# creates people table with attributes name, job, gender and age
def create_table
puts "Creating people table"
$db.execute %q{
CREATE TABLE people(
id integer primary key,
name varchar(50),
job varchar(50),
gender varchar(6),
age integer
)
}
end
# adds a person by the provided attributes
def add_person
puts "Enter Name:"
name = gets.chomp
puts "Enter Job:"
job = gets.chomp
puts "Enter Gender:"
gender = gets.chomp
puts "Enter Age:"
age = gets.chomp
$db.execute("INSERT INTO people (name, job, gender, age) VALUES (?, ?, ?, ?)", name, job, gender, age)
end
# finds a person by id or name
def find_person
puts "Enter the name or ID of a person to find:"
id = gets.chomp
person = $db.execute("SELECT * FROM people WHERE name = ? OR id = ?", id, id.to_i).first
unless person
puts "No record found"
return
end
puts %Q{
Name: #{person["name"]}
job: #{person["job"]}
Gender: #{person["gender"]}
Age: #{person["age"]}
}
end
# progam
loop do
puts %q{Please select an option
1. Create people table
2. Add a person
3. Look for a person
4. Quit
}
case gets.chomp
when "1"
create_table
when "2"
add_person
when "3"
find_person
when "4"
disconnect_and_quit
end
end