Skip to content

Instantly share code, notes, and snippets.

@mdang
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save mdang/b63ffd1ad86ff61ac835 to your computer and use it in GitHub Desktop.

Select an option

Save mdang/b63ffd1ad86ff61ac835 to your computer and use it in GitHub Desktop.
Student CRUD Example
require 'pg'

# Student class
class Student
	@conn

	# Constructor
	def initialize(config)
		@conn = PG.connect(:hostaddr => config[:hostaddr], :port => config[:port], :dbname => config[:dbname])
	end

	# Get every student
	def get_all_students
		res = @conn.exec("SELECT id, first_name, last_name, age FROM students")
	end

	# Get student by id
	def get_student(id)
		res = @conn.exec("SELECT id, first_name, last_name, age FROM students WHERE id = #{id}")
		# Return the one record 
		res[0]
	end

	# Add a new student
	def add(first_name, last_name, age)
		# Return the id that was autoincremented
		res = @conn.exec("INSERT INTO students (first_name, last_name, age) VALUES ('#{first_name}', '#{last_name}', #{age}) RETURNING id")
		# Return the id
		res[0]['id']
	end

	# Update an existing student
	def update(id, first_name, last_name, age)
		res = @conn.exec("UPDATE students SET first_name = '#{first_name}', last_name = '#{last_name}', age = #{age} WHERE id = #{id}")
	end

	# Remove a student 
	def remove(id)
		res = @conn.exec("DELETE FROM students WHERE id = #{id}")
	end

end

# Create an instance of Student
student = Student.new({
	:hostaddr => '127.0.0.1',
	:port => 5432,
	:dbname => 'wdi'
})

# Get all students
students = student.get_all_students
students.each do |item|
	puts item
end

# Add a new student
random_age = rand(18..110)
new_student_id = student.add('Test', 'Student', random_age)
puts "Added new student #{new_student_id}"

# Get a single student
new_student = student.get_student(new_student_id)

puts "New student:"
puts new_student

# Update student 
puts "Updating student to have age of 78"
student.update(new_student_id, new_student['first_name'], new_student['last_name'], 78)

puts "Updated student:"
updated_student = student.get_student(new_student_id)
puts updated_student

# Delete the newly added student
puts "Deleting the new student"
student.remove(new_student_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment