When I try to connect to database via Ruby I'm getting this error :
conn.rb:16:in `<main>': undefined method `query=' for #<Mysql2::Client:0x2ee5190> (NoMethodError)
Did you mean? query
_query
My code is :
require 'mysql2'
connection = Mysql2::Client.new(:host => "localhost", :username => "root",:password => "",:database => "ruby")
result = connection.query = ("INSERT INTO datacheck(#{info.keys}) VALUES #{info.values}")
Seems that everything is working until this line
result = connection.query = ("INSERT INTO datacheck(#{info.keys}) VALUES #{info.values}")
I'm looking for someone who can help.
The error message is pretty clear: it does not exist a query= method, but query does. Try
result = connection.query("INSERT INTO datacheck(#{info.keys}) VALUES #{info.values}")
Related
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)
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.
#!/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.
I'm dealing with this a few days, and cannot connect to a simple mysql database on localhost.
require "mysql"
#db_host = "localhost"
#db_user = "myrubyapp"
#db_pass = "1234"
#db_name = "myrubyapp"
mysql = Mysql.new(:host => #db_host, :username => #db_user, :password => #db_pass, :database => #db_name)
The output I got is an error: can't convert Hash into String (TypeError) where Mysql.new is.
The second one, I tried to change the gem to mysql2
require "mysql2"
#db_host = "localhost"
#db_user = "myrubyapp"
#db_pass = "1234"
#db_name = "myrubyapp"
mysql = Mysql2.new(:host => #db_host, :username => #db_user, :password => #db_pass, :database => #db_name)
The output is an error too, but is different from the first: undefined method "new" for Mysql2:Module (NoMethodError).
Guys I'm sorry that I have to ask this kind of questions, but I'm really really confused, I have an experience of programming more than 3 years in JavaSE and EE, I am ashamed cause I can't deal with that. Please point me into right direction and don't judge me harshly. I am new to Ruby.
Try
mysql = Mysql2::Client.new(:host => #db_host, :username => #db_user, :password => #db_pass, :database => #db_name)
correct syntax is:
client = Mysql2::Client.new(:host => "localhost", :username => "root")
see mysql2 on github for more examples
I recomment you to take a look at Sequel as raw mysql2 lib provide a very limited functionality and Sequel can do a lot.
Never used the gem mysql, but have you tried to remove the hash :host => etc and pass directly a list of parameters?
Something like con = Mysql.new db_host, db_user, db_pass, db_name
http://zetcode.com/db/mysqlrubytutorial/ for a tutorial