Ruby - Test whether database connection is possible
You can check if the connection is possible by running the following script:
require './config/environment.rb' # Assuming the script is located in the root of the rails app
begin
ActiveRecord::Base.establish_connection # Establishes connection
ActiveRecord::Base.connection # Calls connection object
puts "CONNECTED!" if ActiveRecord::Base.connected?
puts "NOT CONNECTED!" unless ActiveRecord::Base.connected?
rescue
puts "NOT CONNECTED!"
end
How do we verify if Sequel.connect opened our SQLite3 database in Rails?
Offhand I'd say you can try:
DB.test_connection
=> true
The documentation for test_connection
says:
Attempts to acquire a database connection. Returns true if successful. Will probably raise an Error if unsuccessful. If a server argument is given, attempts to acquire a database connection to the given server/shard.
Years ago we'd use a benign query to tell if the connection is alive. You can try:
DB["select datetime('now');"].first
Which returns:
{
:"datetime('now')" => "2013-06-25 06:23:44"
}
You'll probably want to catch any exceptions that might be raised if the query fails, but that would indicate that the connection was down too.
How to check mysql database connection is setup and particular table has been created
I have done it by using mysql2 gem.
def is_table_created?(db, table)
begin
connection = Mysql2::Client.new(host: 'localhost', username: 'root', database: db)
connection.query("describe #{table};")
return true
rescue Exception => e
logger.warn(e)
return false
ensure
connection.close if connection
end
end
how to check the database name that ActiveRecord uses
Rails.configuration.database_configuration
This will give you a hash table with the configurations for each of your environments. E.g. to get your development database name:
Rails.configuration.database_configuration["development"]["database"]
Related Topics
Catching Timeout Errors with Ruby Mechanize
Spacing Around Parentheses in Ruby
Parsing Large Xml Files W/ Ruby & Nokogiri
Ruby Errors with Os X Yosemite
Execjs::Programerror in Welcome#Index Typeerror: Object Doesn't Support This Property or Method
Rake Db:Migrate Is Being Aborted Due to Rake Version Difference
Devise Install from Existing Model/Database
Accessing Variables from Included Files in Ruby
Generate a Nested JSON Array in Jbuilder
Using Ruby to Generate Sha512 Crypt-Style Hashes Formatted for /Etc/Shadow
Rails 3.2 Activeadmin 'Collection Is Not a Paginated Scope.' Error
Getting Ruby Function Object Itself
What's the Best Background Job Management Library for Rails
Ruby on Rails Map.Root Doesn't Seem to Be Working
You Don't Have Write Permissions into the /Var/Lib/Gems/1.9.1 Directory