Ruby Tutorial
Ruby CGI
Ruby Advanced
The Ruby DBI (Database Interface) module provides a database-independent interface for Ruby scripts. This means you can switch your database system without having to change your code, provided the new database system has a DBI driver.
The Ruby DBI module has been deprecated and is no longer maintained. It's recommended to use database-specific gems like pg
for PostgreSQL, mysql2
for MySQL, or sqlite3
for SQLite. For an ORM-like interface, ActiveRecord
or Sequel
are commonly used.
However, for educational purposes, here's a basic example of how you could use Ruby DBI:
require 'dbi' begin # Connect to a MySQL database 'test' on localhost dbh = DBI.connect('DBI:Mysql:test:localhost', 'username', 'password') # Prepare and execute a SQL query sth = dbh.prepare('SELECT * FROM people') sth.execute # Print out each row while row = sth.fetch do p row end # Close the statement handle when done sth.finish rescue DBI::DatabaseError => e puts "An error occurred" puts "Error code: #{e.err}" puts "Error message: #{e.errstr}" ensure # Disconnect from the database dbh.disconnect if dbh end
In the script above, we:
DBI.connect
.dbh.prepare
, then execute it with sth.execute
.sth.fetch
, then print it out.sth.finish
.dbh.disconnect
.Again, the dbi
gem is deprecated and not maintained. If you're working with databases in Ruby, consider using the pg
, mysql2
, or sqlite3
gems for direct database access, and ActiveRecord
or Sequel
for an ORM-like interface.
Using DBI for database access in Ruby:
require 'dbi' # Connect to a database (example for MySQL) dbh = DBI.connect('DBI:Mysql:database=testdb;host=localhost', 'username', 'password') # Perform database operations here # Disconnect from the database dbh.disconnect
Ruby DBI example:
require 'dbi' # Connect to a SQLite database dbh = DBI.connect('DBI:SQLite3:test.db') # Execute a query result = dbh.execute('SELECT * FROM users') # Fetch and print results result.fetch do |row| puts "User ID: #{row['user_id']}, Name: #{row['name']}" end # Disconnect from the database dbh.disconnect
Connect to a database using Ruby DBI:
DBI.connect
method is used to establish a connection to a database.require 'dbi' # Connect to a PostgreSQL database dbh = DBI.connect('DBI:Pg:dbname=mydatabase;host=localhost;port=5432', 'username', 'password') # Perform database operations here # Disconnect from the database dbh.disconnect
Ruby DBI MySQL example:
require 'dbi' # Connect to a MySQL database dbh = DBI.connect('DBI:Mysql:database=mydatabase;host=localhost', 'username', 'password') # Perform MySQL database operations here # Disconnect from the database dbh.disconnect
Ruby DBI SQLite example:
require 'dbi' # Connect to an SQLite database dbh = DBI.connect('DBI:SQLite3:test.db') # Perform SQLite database operations here # Disconnect from the database dbh.disconnect
Ruby DBI PostgreSQL example:
require 'dbi' # Connect to a PostgreSQL database dbh = DBI.connect('DBI:Pg:dbname=mydatabase;host=localhost;port=5432', 'username', 'password') # Perform PostgreSQL database operations here # Disconnect from the database dbh.disconnect
Ruby DBI Oracle example:
require 'dbi' # Connect to an Oracle database dbh = DBI.connect('DBI:OCI8:dbname=ORCL', 'username', 'password') # Perform Oracle database operations here # Disconnect from the database dbh.disconnect
Ruby DBI connection string:
require 'dbi' # Example connection string for MySQL connection_string = 'DBI:Mysql:database=mydatabase;host=localhost' # Connect to the database dbh = DBI.connect(connection_string, 'username', 'password') # Perform database operations here # Disconnect from the database dbh.disconnect
Working with transactions in Ruby DBI:
require 'dbi' # Connect to a database dbh = DBI.connect('DBI:SQLite3:test.db') # Begin a transaction dbh['AutoCommit'] = false begin # Perform multiple database operations dbh.execute('INSERT INTO users (name) VALUES (?)', 'John Doe') dbh.execute('UPDATE accounts SET balance = balance - 100 WHERE user_id = 1') # Commit the transaction dbh.commit rescue DBI::DatabaseError => e # Handle errors and rollback on failure puts "Transaction failed: #{e.message}" dbh.rollback ensure # Revert to auto-commit mode dbh['AutoCommit'] = true end # Disconnect from the database dbh.disconnect
Error handling in Ruby DBI:
require 'dbi' begin # Connect to a database dbh = DBI.connect('DBI:Mysql:database=mydatabase;host=localhost', 'username', 'password') # Perform database operations here rescue DBI::DatabaseError => e # Handle database errors puts "Database Error: #{e.message}" ensure # Disconnect from the database dbh.disconnect if dbh end
Ruby DBI prepared statements:
require 'dbi' # Connect to a database dbh = DBI.connect('DBI:Mysql:database=mydatabase;host=localhost', 'username', 'password') # Create a prepared statement statement = dbh.prepare('INSERT INTO users (name) VALUES (?)') # Execute the prepared statement with parameters statement.execute('John Doe') # Disconnect from the database dbh.disconnect
Ruby DBI query execution:
execute
method.require 'dbi' # Connect to a database dbh = DBI.connect('DBI:SQLite3:test.db') # Execute a query result = dbh.execute('SELECT * FROM users') # Process the query results result.fetch do |row| puts "User ID: #{row['user_id']}, Name: #{row['name']}" end # Disconnect from the database dbh.disconnect
Ruby DBI fetch results:
fetch
method to retrieve results from a query.require 'dbi' # Connect to a database dbh = DBI.connect('DBI:Mysql:database=mydatabase;host=localhost', 'username', 'password') # Execute a query result = dbh.execute('SELECT * FROM users') # Fetch and print results result.fetch do |row| puts "User ID: #{row['user_id']}, Name: #{row['name']}" end # Disconnect from the database dbh.disconnect