Using PostgreSQL with Ruby
Description
In this tutorial, we will explore how to use PostgreSQL with Ruby, covering setup, connecting to a PostgreSQL database, and performing basic operations using the pg
gem.
Setup
Before starting, ensure you have Ruby installed on your system. Install the pg
gem, which provides a Ruby interface for PostgreSQL:
gem install pg
Connecting to PostgreSQL
To connect to a PostgreSQL database in Ruby, use the following code snippet:
require 'pg'
# Replace with your PostgreSQL connection details
db_params = {
host: 'localhost',
dbname: 'mydatabase',
user: 'myuser',
password: 'mypassword'
}
begin
conn = PG.connect(db_params)
puts "Connected to database #{conn.db}"
rescue PG::Error => e
puts e.message
ensure
conn.close if conn
end
Connected to database mydatabase
Performing Basic Operations
Here are examples of basic CRUD operations using Ruby with PostgreSQL:
Create (INSERT)
require 'pg'
db_params = {
host: 'localhost',
dbname: 'mydatabase',
user: 'myuser',
password: 'mypassword'
}
begin
conn = PG.connect(db_params)
# Execute INSERT statement
conn.exec("INSERT INTO employees (name, age) VALUES ('Alice', 30)")
puts "Record inserted successfully."
rescue PG::Error => e
puts e.message
ensure
conn.close if conn
end
Record inserted successfully.
Read (SELECT)
require 'pg'
db_params = {
host: 'localhost',
dbname: 'mydatabase',
user: 'myuser',
password: 'mypassword'
}
begin
conn = PG.connect(db_params)
# Execute SELECT statement
result = conn.exec("SELECT * FROM employees WHERE age > 25")
result.each do |row|
puts "Name: #{row['name']}, Age: #{row['age']}"
end
rescue PG::Error => e
puts e.message
ensure
conn.close if conn
end
Name: Alice, Age: 30
Update
require 'pg'
db_params = {
host: 'localhost',
dbname: 'mydatabase',
user: 'myuser',
password: 'mypassword'
}
begin
conn = PG.connect(db_params)
# Execute UPDATE statement
conn.exec("UPDATE employees SET age = 31 WHERE name = 'Alice'")
puts "Record updated successfully."
rescue PG::Error => e
puts e.message
ensure
conn.close if conn
end
Record updated successfully.
Delete
require 'pg'
db_params = {
host: 'localhost',
dbname: 'mydatabase',
user: 'myuser',
password: 'mypassword'
}
begin
conn = PG.connect(db_params)
# Execute DELETE statement
conn.exec("DELETE FROM employees WHERE name = 'Alice'")
puts "Record deleted successfully."
rescue PG::Error => e
puts e.message
ensure
conn.close if conn
end
Record deleted successfully.
Conclusion
Explanation: This concludes the tutorial on using PostgreSQL with Ruby. You've learned how to install the necessary dependencies, connect to a PostgreSQL database, and perform basic CRUD operations.