Certainly! Here’s an example of Ruby code that demonstrates how to delete 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 with a placeholder
sql = 'DELETE FROM your_table WHERE condition_column = $1'
# Set the value used in the condition
condition_value = 'ConditionValue'
begin
# Execute the SQL statement with the condition value
result = conn.exec_params(sql, [condition_value])
rows_deleted = result.cmd_tuples
puts "Data deleted successfully. Rows affected: #{rows_deleted}"
rescue PG::Error => e
puts 'Error deleting 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 delete data.condition_column
: The name of the column to use as a condition for deleting the data.'ConditionValue'
: The value used in the condition to identify the specific rows to delete.
This code uses the pg
gem to establish a connection to the PostgreSQL database, prepare an SQL DELETE statement with a placeholder, provide the value used in the condition using exec_params
, retrieve the number of rows affected using cmd_tuples
, and handle any potential errors that may occur. The code also outputs the number of affected rows upon successful deletion. Make sure to install the pg
gem before running this code by executing gem install pg
in your Ruby environment.