I am trying to connect to a mysql db with a ruby script. The code looks like
def self.connect_to_db()
db_params = self.get_db_connection_params()
begin
connection = ActiveRecord::Base.establish_connection(db_params)
puts "Successfully connected to DB"
self.verify_connection(connection)
rescue Exception => e
puts "Error while connecting to DB: #{e}"
end
end
def self.verify_connection(connection)
begin
puts "Verifying connection.."
q = "select * from users;"
#result = connection.connection.execute(q)
#result.each(:as => :hash) do |row|
puts row["name"]
end
puts "Verified"
rescue Exception => e
puts "Error while verifying: #{e}"
end
end
but iam getting exception:
Error while verifying:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server.
The database exists on a different host.
I am able to connect to the db using mysql client through command line.
Related
Context: I am writing a simple dynamic query in Ruby using the mysql2 gem.
Attempt:
#!/usr/local/bin/ruby
require "mysql2"
puts "Please enter the title of this Report:"
title = gets.chomp
Mysql2::Client.default_query_options.merge!(:as => :array)
puts "Please enter the host, username, password and database in order:"
hst = gets.chomp
user = gets.chomp
pass = gets.chomp
db = gets.chomp
begin
mysql = Mysql2::Client.new(:host => hst, :username => user, :password => pass, :database => db)
rescue Mysql2::Error => e
puts e.errno
puts e.error
retry
puts "Error: please try again."
puts "Enter the host, username, password and database:"
hst = gets.chomp!
user = gets.chomp!
pass = gets.chomp!
db = gets.chomp!
end
puts "Successfully accessed #{db}!"
Note that:
rescue Mysql2::Error => e
puts e.errno
puts e.error
works with the mysql gem, but:
rescue Mysql2::StandardError => e
puts e.errno
puts e.error
does not work with the mysql2 gem.
Finally, the error in Terminal:
iMac:workspace guy$ ruby File.rb
Please enter the title of this Report:
title
Please enter the host, username, password and database in order:
1.2.3.4
username15
password123
db_one
File.rb:19:in `rescue in <main>': uninitialized constant Mysql2::StandardError (NameError)
Did you mean? StandardError
from File.rb:17:in `<main>'
Edit after answer: leaving :host as :hst gave me the following error:
2002
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
mysql2 gem has defined Mysql2::Error, not `Mysql2::StandardError.
You need to rescue Mysql2::Error
Refer to mysql2 Github source for more info.
I'm using Docker to run my Ruby app, with MySQL as a database. I need for my Ruby app to wait until MySQL has finished loading and a connection can be made.
I'm using the following code:
def connect_to_db
begin
puts "Trying to connect to Mysql"
Sequel::Model.db = Sequel.connect( // Connection stuff in here )
rescue Sequel::Error => e
puts "Mysql connection failed #{e.message}: Retrying."
retry
end
end
connect_to_db()
This runs once, then I get an error - Sequel::DatabaseConnectionError: Mysql2::Error: Unknown MySQL server host (25) - It doesn't go into the rescue block and doesn't retry.
I've tried rescue Sequel::DatabaseConnectionError but this gives the same result.
What do I need to rescue here?
Got it working with db.test_connection:
def connect_to_db_with_mysql_driver
begin
puts "Trying to connect to Mysql"
db = Sequel.connect(
// Connection stuff
)
if db.test_connection == true
Sequel::Model.db = db
else
raise "Mysql connection failed."
end
rescue => ex
puts ex
puts "Retrying..."
retry
end
end
#!/usr/bin/ruby -w
require "rubygems"
require "mysql"
begin
# connect to the MySQL server
dbh = DBI.connect("DBI:Mysql:TESTDB:localhost",
"nyros", "root")
# get server version string and display it
row = dbh.select_one("SELECT VERSION()")
puts "Server version: " + row[0]
rescue DBI::DatabaseError => e
puts "An error occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
ensure
# disconnect from server
dbh.disconnect if dbh
end
I want to connect and access MySQL database through ruby programming. But i am getting this error when executing the ruby code in my terminal.
Error:
/.rvm/rubies/ruby-1.9.3 p547/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:55:in 'require': cannot load such file -- mysql (LoadError)
from /home/nyros/.rvm/rubies/ruby-1.9.3-p547/lib/ruby/site_ruby/1.9.1/rubygems/core_ext/kernel_require.rb:55:in 'require'
from task.rb:3:in '<main>'
I suggest using mysql2. It is a mysql library for Ruby.
For example:
require 'mysql2'
client = Mysql2::Client.new(:host => HOST, :username => USERNAME, :database => DATABASE)
client.query("select * from tabel_name;")
If you don't want to use mysql2, you also can refer to this link.
I know this problem has been asked many times. But I tried the solutions and they didn't work for me. I have a web application built on rails 3.2.12 and ruby 1.9.2p180. I have a stored procedure in it which returns me data of a query having 5 inner joins. Multiple rows approximately 600 are returned in present case. On the local the stored procedure runs fine with no issues. But when I tried it on the server it is throwing:
ActiveRecord::StatementInvalid: Mysql2::Error: PROCEDURE test.sp_procedure can't return a result set in the given context: call sp_procedure('2015-02-14 00:00:00 -0500', '2015-03-03 23:59:00 -0500', 5, '13')
I have searched for this issue and found that I need to set CLIENT_MULTI_RESULTS flag when establishing connection to MySQL server. For this I have done monkey patching as said. Here is the file in initializers:
module ActiveRecord
class Base
def self.mysql2_connection(config)
config[:username] = 'deploy' if config[:username].nil?
if Mysql2::Client.const_defined? :FOUND_ROWS
config[:flags] = config[:flags] ? config[:flags] | Mysql2::Client::FOUND_ROWS : Mysql2::Client::FOUND_ROWS
end
client = Mysql2::Client.new(config.symbolize_keys)
options = [config[:host], config[:username], config[:password], config[:database], config[:port], config[:socket], 0]
ConnectionAdapters::Mysql2Adapter.new(client, logger, options, config)
end
def self.select_sp(sql, name = nil)
connection = ActiveRecord::Base.connection
begin
connection.select_all(sql, name)
rescue NoMethodError
ensure
connection.reconnect! unless connection.active?
end
end
end
end
In my database.yml I have added: flags: <%= 65536 | 131072 %> and also tried with flags: 131072. But it didn't work.
However using the following works:
client = Mysql2::Client.new(:host => "localhost", :username => "root", :flags => Mysql2::Client::MULTI_STATEMENTS )
result = client.query( 'CALL sp_procedure('2015-02-14 00:00:00 -0500', '2015-03-03 23:59:00 -0500', 5, '13')')
This worked on the server too. But each time the stored procedure will run it will create a new connection which I don't want.
And also one thing to note while I am doing this on local as soon as I call the stored procedure I have to execute this:
ActiveRecord::Base.connection.reconnect!
If I don't write this it throws an error:
ActiveRecord::StatementInvalid: Mysql2::Error: Commands out of sync; you can't run this command now
So this is also the same thing means it creates a new connection each time. So I am finding for a solution which saves me from doing this.
And if the monkey patching is correct then what am I missing. Please help.
So I created an account at open shift, created an app, and installed the command line tool. when I do the command rhc domain status it fails:
Loaded suite /usr/bin/rhc-chk
Started
.E
===============================================================================
Error: test_connectivity(Test1_Connectivity)
ArgumentError: too few arguments
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:204:in `sprintf'
201: message = sprintf(get_message(:errors,name),*(args.shift || ''))
202: solution = get_message(:solutions,name)
203: if solution
=> 204: message << "\n" << sprintf(solution,*(args.shift || ''))
205: end
206: message
207: end
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:204:in `error_for'
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:270:in `test_connectivity'
===============================================================================
F
===============================================================================
Failure:
You need to be able to connect to the server in order to test authentication.
<false> is not true.
test_authentication(Test2_Authentication)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:280:in `test_authentication'
277: # Checking Authentication
278: #
279: def test_authentication
=> 280: assert $connectivity, error_for(:cant_connect)
281:
282: data = {'rhlogin' => $rhlogin}
283: response = fetch_url_json("/broker/userinfo", data)
===============================================================================
..F
===============================================================================
Failure: You must have an account on the server in order to test: whether you have a valid key loaded in your agent.
test_03_remote_ssh_keys(Test3_SSH)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:317:in `require_login'
314: end
315:
316: def require_login(test)
=> 317: flunk(error_for(:no_account,test)) if $user_info.nil?
318: end
319:
320: def require_remote_keys(test)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:321:in `require_remote_keys'
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:376:in `test_03_remote_ssh_keys'
===============================================================================
F
===============================================================================
Failure: You must have an account on the server in order to test: connecting to your applications.
test_04_ssh_connect(Test3_SSH)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:317:in `require_login'
314: end
315:
316: def require_login(test)
=> 317: flunk(error_for(:no_account,test)) if $user_info.nil?
318: end
319:
320: def require_remote_keys(test)
/Library/Ruby/Gems/1.8/gems/rhc-0.94.8/bin/rhc-chk:383:in `test_04_ssh_connect'
===============================================================================
Finished in 2.403595 seconds.
7 tests, 8 assertions, 3 failures, 1 errors, 0 pendings, 0 omissions, 0 notifications
42.8571% passed
Not really understanding why it's not able to connect. I was able to use: rhc domain show, with no problems.
Anyone have any suggestions on how to fix this?
It's a bug that should get fixed in the upcoming release. Even though you see this error it shouldn't affect any other behaviour.