Ruby - Test Whether Database Connection Is Possible

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



Leave a reply



Submit