Certainly! Here’s an example of Ruby code that demonstrates how to add data to 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 with placeholders
sql = 'INSERT INTO your_table (column1, column2) VALUES ($1, $2)'
# Set the values to be inserted
column1_value = 'DataValue1'
column2_value = 'DataValue2'
begin
# Execute the SQL statement with the values
conn.exec_params(sql, [column1_value, column2_value])
puts 'Data inserted successfully.'
rescue PG::Error => e
puts 'Error inserting 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 where you want to add data.column1, column2
: The names of the columns in the table where you want to add data.'DataValue1', 'DataValue2'
: The values you want to add tocolumn1
andcolumn2
respectively.
This code uses the pg
gem to establish a connection to the PostgreSQL database, prepare an SQL INSERT statement with placeholders, provide the values to be inserted using exec_params
, and handle any potential errors that may occur. The code also outputs a success message if the data insertion is successful. Make sure to install the pg
gem before running this code by executing gem install pg
in your Ruby environment.