How to connect and accessing mysqldb with ruby programming - mysql

#!/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.

Related

Ruby connect to mysql using login path

I'm trying to create a connection to mysql from ruby script using login path.
I've set the login path in the following way:
mysql_config_editor set --login-path=login-path --host=host-name --user=user --password
Now in my ruby script I have the following line:
require 'mysql2'
$mysql_connection = Mysql2::Client.new(:default_file => '~/.mylogin.cnf',:default_group => 'login-path')
And I get the following error:
error: Found option without preceding group in config file:
/home/user/.mylogin.cnf at line: 3 Fatal error in defaults handling.
Program aborted
When I'm connecting like this, it succeed:
require 'mysql2'
$mysql_connection = Mysql2::Client.new(:host => 'host-name', :username => "user", :password => "password", :database => 'database_name')
What am I doing wrong?
I think the problem is with your 'default_group' setting. I have standard mysql setup using a typical login-path of 'client', eg:
% mysql_config_editor print
[client]
password = *****
and the following connect works with no issue:
#client = Mysql2::Client.new(host: MySQL_Host, username: MySQL_User, default_group: 'client', database: MySQL_Database)

Ruby and mysql2: Looping Until Connection is Error Free

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.

Ruby: Catching Sequel::DatabaseConnectionError

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

connect mysql with ruby without rails gives error in ruby version 2

I have included given code in my db.rb file
require "mysql2" # if needed
#db_host = "localhost"
#db_user = "root"
#db_pass = "root"
#db_name = "farji"
client = Mysql::Client.new(:host => #db_host, :username => #db_user, :password => #db_pass, :database => #db_name)
#cdr_result = client.query("SELECT * from employee')
and in terminal i have install
sudo apt-get install libmysqlclient15-dev
gem install mysql2
and run ruby db.rb it gives me error db.rb:8:in `': uninitialized constant Mysql (NameError)
my ruby version is ruby-2.1.5
Please guide me how to solve this.

mysql dbi connection: works in irb, not in script?

I am trying to use the rubygem DBI to connect to MYSQL on Windows 7; I can connect using irb but not from within a ruby script, which has stumped me for a few days now...
Here is my gem env output:
RubyGems Environment:
- RUBYGEMS VERSION: 1.8.28
- RUBY VERSION: 1.9.3 (2014-02-24 patchlevel 545) [i386-mingw32]
- INSTALLATION DIRECTORY: C:/Ruby193/lib/ruby/gems/1.9.1
- RUBY EXECUTABLE: C:/Ruby193/bin/ruby.exe
- EXECUTABLE DIRECTORY: C:/Ruby193/bin
- RUBYGEMS PLATFORMS:
- ruby
- x86-mingw32
- GEM PATHS:
- C:/Ruby193/lib/ruby/gems/1.9.1
- C:/Users/rick/.gem/ruby/1.9.1
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :benchmark => false
- :backtrace => false
- :bulk_threshold => 1000
- REMOTE SOURCES:
- http://rubygems.org/
Here is my irb connection:
irb(main):001:0> require 'dbi'
=> true
irb(main):004:0> dbh=DBI.connect("DBI:Mysql:host=127.0.0.1;port=3306", "rick",>
=> #<DBI::DatabaseHandle:0x2c30bb0 #handle=#<DBI::DBD::Mysql::Database:0x2c30dd8
#handle=#<Mysql:0x2c30f28>, #attr={"AutoCommit"=>true}, #have_transactions=true
, #mutex=#<Mutex:0x2c30bf8>>, #trace_output=nil, #trace_mode=nil, #convert_types
=true, #driver_name="Mysql">
irb(main):005:0> row = dbh.select_one("SELECT VERSION()")
=> ["5.5.25a"]
irb(main):006:0> puts row
5.5.25a
=> nil
irb(main):007:0>
And here is my script:
require 'DBI'
require 'mysql'
# connect to the MySQL server
begin
dbh = DBI.connect("DBI:Mysql:wikifracdb:127.0.0.1;port=3306", "rick", "rick")
# 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
But when I run my script, I get:
C:/Ruby193/lib/ruby/gems/1.9.1/gems/dbi-0.4.5/lib/dbi.rb:93: warning: already in
itialized constant VERSION
C:/Ruby193/lib/ruby/gems/1.9.1/gems/dbi-0.4.5/lib/dbi.rb:96: warning: already in
itialized constant API_VERSION
C:/Ruby193/lib/ruby/gems/1.9.1/gems/dbi-0.4.5/lib/dbi.rb:100: warning: already i
nitialized constant DEFAULT_TRACE_MODE
C:/Ruby193/lib/ruby/gems/1.9.1/gems/dbi-0.4.5/lib/dbi.rb:101: warning: already i
nitialized constant DEFAULT_TRACE_OUTPUT
An error occurred
Error code: 2003
Error message: Can't connect to MySQL server on 'localhost' (10061)
I have Windows Firewall turned off.
Any suggestions will be much appreciated...this has been driving me crazy!