Database Access in Ruby Language

Database Access in Ruby Language

Ruby, a dynamic and versatile programming language, offers a range of tools and libraries to interact with data

bases effectively. In this post, we’ll explore the fundamentals of database access in Ruby, including connecting to databases, executing queries, and handling data.

Connecting to a Database

Ruby provides numerous libraries and frameworks for working with various databases, but one of the most commonly used libraries is ActiveRecord, which is part of the Ruby on Rails framework. To get started, let’s establish a connection to a database:

require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'sqlite3',
  database: 'my_database.db'
)

In this example, we use the SQLite database adapter, but you can replace it with the appropriate adapter for your chosen database system.

Executing Queries

Once you’re connected to the database, you can execute SQL queries using ActiveRecord. Here’s an example of creating a table and inserting data:

class User < ActiveRecord::Base
end

# Create a new table
ActiveRecord::Schema.define do
  create_table :users do |t|
    t.string :name
    t.integer :age
  end
end

# Insert data
User.create(name: 'John', age: 30)
User.create(name: 'Jane', age: 25)

The User class represents a table in the database. We define its structure using create_table, and then we use the create method to insert data.

Retrieving Data

Retrieving data from the database is straightforward. You can use various methods to fetch records that match specific criteria. Here’s an example:

# Retrieve all users
all_users = User.all

# Retrieve users older than 28
users_above_28 = User.where('age > 28')

These examples demonstrate how to query the database and retrieve records that meet certain conditions.

Updating and Deleting Data

To update or delete records, ActiveRecord provides methods like update and destroy. Here’s how you can use them:

# Update a user's age
user = User.find_by(name: 'John')
user.update(age: 31)

# Delete a user
user = User.find_by(name: 'Jane')
user.destroy

These methods make it easy to modify or remove records from the database.

Error Handling

Handling errors when working with databases is crucial. Ruby provides mechanisms for managing exceptions, ensuring that your code is robust and resilient in the face of unexpected issues. Here’s an example of handling database exceptions:

begin
  # Attempt to perform a database operation
rescue ActiveRecord::RecordNotFound => e
  puts "Record not found: #{e.message}"
rescue ActiveRecord::RecordInvalid => e
  puts "Invalid record: #{e.message}"
rescue ActiveRecord::StatementInvalid => e
  puts "SQL statement invalid: #{e.message}"
end

By using begin and rescue blocks, you can gracefully handle various database-related exceptions.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading