Certainly! Here’s an example of Ruby code that demonstrates how to retrieve and list data from a PostgreSQL database using the pg
gem:
require 'pg'
# Connect to the PostgreSQL database
conn = PG.connect(
dbname: 'your_database',
user: 'your_username',
password: 'your_password',
host: 'localhost',
port: 5432
)
# Prepare the SQL statement
sql = 'SELECT * FROM your_table'
begin
# Execute the SQL statement
result = conn.exec(sql)
# Process and display the retrieved data
result.each do |row|
puts "Column1: #{row['column1']}"
puts "Column2: #{row['column2']}"
puts "Column3: #{row['column3']}"
puts "-------------------------"
end
rescue PG::Error => e
puts 'Error retrieving data:', e.message
ensure
# Close the database connection
conn.close
end
Make sure to replace the following placeholders with your own values:
your_database
: The name of the PostgreSQL database.your_username
: The username for accessing the database.your_password
: The password for accessing the database.localhost
: The hostname or IP address of your PostgreSQL server.your_table
: The name of the table from which you want to retrieve data.column1, column2, column3
: The names of the columns in the table.
This code uses the pg
gem to establish a connection to the PostgreSQL database, execute an SQL SELECT statement using exec
, iterate over the result set using each
, and process and display the retrieved data. The code also handles any potential errors that may occur during the execution. Make sure to install the pg
gem before running this code by executing gem install pg
in your Ruby environment.