Issues while connecting to mysql using ruby - mysql

require 'rubygems'
require 'mysql'
db = Mysql.connect('localhost', 'root', '', 'mohit')
//db.rb:4: undefined method `connect' for Mysql:Class (NoMethodError)
//undefined method `real_connect' for Mysql:Class (NoMethodError)
db.query("CREATE TABLE people ( id integer primary key, name varchar(50), age integer)")
db.query("INSERT INTO people (name, age) VALUES('Chris', 25)")
begin
query = db.query('SELECT * FROM people')
puts "There were #{query.num_rows} rows returned"
query.each_hash do |h|
puts h.inspect
end
rescue
puts db.errno
puts db.error
end
error i am geting is:
undefined method `connect' for Mysql:Class (NoMethodError)
OR
undefined method `real_connect' for Mysql:Class (NoMethodError)
EDIT
return value of Mysql.methods
["private_class_method", "inspect", "name", "tap", "clone", "public_methods", "object_id", "__send__", "method_defined?", "instance_variable_defined?", "equal?", "freeze", "extend", "send", "const_defined?", "methods", "ancestors", "module_eval", "instance_method", "hash", "autoload?", "dup", "to_enum", "instance_methods", "public_method_defined?", "instance_variables", "class_variable_defined?", "eql?", "constants", "id", "instance_eval", "singleton_methods", "module_exec", "const_missing", "taint", "instance_variable_get", "frozen?", "enum_for", "private_method_defined?", "public_instance_methods", "display", "instance_of?", "superclass", "method", "to_a", "included_modules", "const_get", "instance_exec", "type", "<", "protected_methods", "<=>", "class_eval", "==", "class_variables", ">", "===", "instance_variable_set", "protected_instance_methods", "protected_method_defined?", "respond_to?", "kind_of?", ">=", "public_class_method", "to_s", "<=", "const_set", "allocate", "class", "new", "private_methods", "=~", "tainted?", "__id__", "class_exec", "autoload", "untaint", "nil?", "private_instance_methods", "include?", "is_a?"]
return value of Mysql.methods(false)
is []... blank array
EDIT2
mysql.rb file
# support multiple ruby version (fat binaries under windows)
begin
require 'mysql_api'
rescue LoadError
if RUBY_PLATFORM =~ /mingw|mswin/ then
RUBY_VERSION =~ /(\d+.\d+)/
require "#{$1}/mysql_api"
end
end
# define version string to be used internally for the Gem by Hoe.
class Mysql
module GemVersion
VERSION = '2.8.1'
end
end

I had this same problem and solved this way:
make sure you have installed only the gem ruby-mysql
and not the gem mysql. For me, now:
$ gem list --local | grep mysql
ruby-mysql (2.9.2)
If that is not the case, uninstall
$ sudo gem uninstall mysql
(I uninstalled every gem with mysql in its name)
and then reinstalled ruby-mysql.
In my case, because I have mysql installed in a usb disk
the installation command was:
sudo env ARCHFLAGS="-arch i386" gem install ruby-mysql --
--with-mysql-config=/Volumes/usb/opt/bin/osx/mysql/bin/mysql_config
--with-mysql-lib=/Volumes/usb/opt/bin/osx/mysql/lib/
--with-mysql-dir=/Volumes/usb/opt/bin/osx/mysql
(and I was using the 32bits binary for MacOs, don't know if that applies for you)
Finally, my ruby test program was
require 'rubygems'
require 'mysql'
dbh = Mysql.real_connect('localhost', 'root', 'your password', 'TEST')
res = dbh.query("select * from Persons;");
puts res.class
res.each do |row|
puts row.join(" ")
end

Short answer:
Remove mysql-ruby
Rebuild mysql-ruby
Reinstall mysql-ruby.
Alternative answer
Remove mysql-ruby
Install ruby-mysqlThe pure ruby MySQL protocol client.
Longer Explanation:
This just happened to me. My 2.8.1 mysql-ruby bindings had been built against libmysqlclient.so.15, and worked fine until I upgraded my MySQL installation and replaced that client library with .so.16. Rebuild resolved this issue.
The 3rd-party gem you used (I used it, too) introduces faulty logic in the mysql.rb file it supplies to trap an error on Windows systems. Notice that in the excerpt you posted, that this mysql.rb file does not re-raise the LoadError on non-Windows platforms. Bummer.
Edit
I contacted the gemspec author, and he has corrected the error! (2010-05-25) With luck no one else will be baffled by this silent failure.

Related

OS X, Elixir, Ecto, Crypto, MySQL

Trying out Elixir & Ecto (not Phoenix) in a sample app to help me learn the language.
Running my program results in the following error:
=INFO REPORT==== 7-Apr-2016::16:23:28 ===
application: logger
exited: stopped
type: temporary
** (Mix) Could not start application tpos: exited in: Tpos.start(:normal, [])
** (EXIT) exited in: GenServer.call(#PID<0.164.0>, {:get_all, Tpos.Data.Models.ProfitCenter}, 5000)
** (EXIT) exited in: GenServer.call(#PID<0.163.0>, {:checkout, :run}, 5000)
** (EXIT) exited in: GenServer.call(#PID<0.168.0>, {:connect, [hostname: "localhost", timeout: 5000, otp_app: :tpos, repo: Tpos.Repo, adapter: Ecto.Adapters.MySQL, database: "tpos", username: "tpos", password: "tpos", port: 3306]}, 5000)
** (EXIT) an exception was raised:
** (UndefinedFunctionError) undefined function :crypto.hash/2 (module :crypto is not available)
(crypto) :crypto.hash(:sha, "tpos")
(mariaex) lib/mariaex/protocol.ex:150: Mariaex.Protocol.mysql_native_password/2
(mariaex) lib/mariaex/protocol.ex:47: Mariaex.Protocol.dispatch/2
(mariaex) lib/mariaex/connection.ex:284: Mariaex.Connection.process/2
(mariaex) lib/mariaex/connection.ex:251: Mariaex.Connection.handle_info/2
(stdlib) gen_server.erl:615: :gen_server.try_dispatch/4
(stdlib) gen_server.erl:681: :gen_server.handle_msg/5
(stdlib) proc_lib.erl:240: :proc_lib.init_p_do_apply/3
If I do a mix deps.clean --all and a mix.deps get and run the program again, it works. But only once. If I exit and attempt to run it again, I receive the above error.
The line that causes the error is:
data = Repo.all(ProfitCenter)
As I said, the first time through this runs fine and returns the expected data. It's only on subsequent runs that the error pops up.
From mix.exs:
defmodule Tpos.Mixfile do
use Mix.Project
def project do
[app: :tpos,
version: "0.0.1",
elixir: "~> 1.2",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
def application do
[ applications: [:mariaex, :ecto],
mod: { Tpos, [] } ]
end
defp deps do
[
{:credo, "~> 0.3", only: [:dev, :test]},
{:mariaex, "~> 0.5.0"},
{:ecto, "~> 1.1.5"},
{:exactor, "~> 2.2.0"}
]
end
end
I'm running OS X 10.11.1, and have tried several things to get it going based on advice like this.
Thoughts? Thanks!
The error states that you don't have :crypto module. You can verify that by running:
iex(1)> Application.start(:crypto)
:ok
If you get anything else than :ok, it means that your Erlang installation is not fully functional. It happens very often when you install Erlang via kerl. Kerl doesn't consider lack of openssl an error. It just skips crytpo libraries without warning.
To install fully functional Erlang with kerl you need to run:
brew install openssl
brew install unixodbc
After that create ~/.kerlrc file with following contents:
KERL_INSTALL_MANPAGES=yes
KERL_CONFIGURE_OPTIONS="--disable-hipe --enable-smp-support --enable-threads
--enable-kernel-poll --with-wx
--with-ssl=/usr/local/opt/openssl
--with-odbc=/usr/local/opt/unixodbc"
And try to reinstall Erlang. This config also adds wx-widgets which are handy if you want to run :observer application. Unixodbc also may come in handy, but less often.
If you are using different tool to install Erlang, you still need to point it to openssl path during compilation.
Alternatively, you can use packages provided by Erlang Solutions: https://www.erlang-solutions.com/resources/download.html They should install all required dependencies including crypto.

How to connect and accessing mysqldb with ruby programming

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

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!

vagrant : chef_solo | how i can change log path from mysql server and mongodb?

I'm working with vagrant and chef .
As far as everything goes , only when I use the Logpath of mysql and mongodb change in the vagrant file , I get an error.
if anyone here has a tip and can help me would be happy.
In Vagrantfile I have stated so ...
:mysql => {
:server_root_password => 'password',
:server_debian_password => 'password',
:server_repl_password => 'password',
:allow_remote_root => true,
:log_dir => "/vagrant/www/logs/mysql",
:tunable => {
:log_slow_queries => "/vagrant/www/logs/mysql/slow.log",
:log_error => true,
:log_warnings => true
}
},
:mongodb => {
:logpath => "/vagrant/www/logs/mongodb"
},
================================================================================
Error executing action `create` on resource 'directory[/vagrant/www/logs/mysql]'
================================================================================
Errno::EPERM
------------
Operation not permitted - /vagrant/www/logs/mysql
Resource Declaration:
---------------------
# In /tmp/vagrant-chef/chef-solo-1/cookbooks/mysql/recipes/server.rb
117: directory path do
118: owner 'mysql' unless platform?('windows')
119: group 'mysql' unless platform?('windows')
120: action :create
121: recursive true
122: end
123: end
Compiled Resource:
------------------
# Declared in /tmp/vagrant-chef/chef-solo-1/cookbooks/mysql/recipes/server.rb:117:in `block in from_file'
directory("/vagrant/www/logs/mysql") do
provider Chef::Provider::Directory
action [:create]
retries 0
retry_delay 2
path "/vagrant/www/logs/mysql"
recursive true
cookbook_name :mysql
recipe_name "server"
owner "mysql"
group "mysql"
mode 493
end
[2013-10-31T01:03:09-07:00] DEBUG: Re-raising exception: Errno::EPERM - directory[/vagrant/www/logs/mysql] (mysql::server line 117) had an error: Errno::EPERM: Operation not permitted - /vagrant/www/logs/mysql
This line is the key problem: Operation not permitted - /vagrant/www/logs/mysql
which means it does not allow user to create directory under this path. Please check if user mysql is privileged to access directory /vagrant/www/logs. Maybe you need +x on /vagrant
First, I would not advise using this -- slow log writes will slow down most databases and I wouldn't want to do that to myself.
Anyhow, permissions on vagrant shared folders can be a bit tricky -- in some, if not many, cases you need to set owner / permission from the vagrantfile. This is a bit tricky for /vagrant but you could map another folder if you really don't want to vagrant ssh into the server to read the logs. To do so:
config.vm.synced_folder "logs", "/logs", :mount_options => ['dmode=777', 'fmode=777']
777 is probably overkill but you get the idea.

JRuby / Warbler / GlassFish - (NameError) uninitialized constant ApplicationController::SessionsHelper

Really Short Story:
I'm incredibly frustrated by this issue
Short Story:
JRuby-1.7.2 building to a .war using Warbler (1.3.8) deploying to a glassfish v3 server. I can build on my machine and everything works fine, however when I try to build with Jenkins, the war gives the following error when trying to load the first page:
org.jruby.exceptions.RaiseException: (NameError) uninitialized constant ApplicationController::SessionsHelper
Long Story:
Build script on our Jenkins server:
#path to rvm
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
# Use the correct ruby
rvm use "jruby-1.7.2#webadmin"
# Set "fail on error" in bash
set -e
# build
bundle update
warble compiled war
Error log from Glassfish....which I hope has enough info.
[#|2013-05-31T17:10:14.634-0400|INFO|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=19;_ThreadName=Thread-2;|PWC1412: WebModule[null] ServletContext.log():INFO: pool was empty - getting new application instance|#]
[#|2013-05-31T17:10:25.181-0400|INFO|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=19;_ThreadName=Thread-2;|PWC1412: WebModule[null] ServletContext.log():An exception happened during JRuby-Rack startup
uninitialized constant ApplicationController::SessionsHelper
--- System
jruby 1.7.4 (1.9.3p392) 2013-05-16 2390d3b on OpenJDK 64-Bit Server VM 1.6.0_27-b27 [linux-amd64]
Time: 2013-05-31 17:10:25 -0400
Server: GlassFish Server Open Source Edition 3.1.2.2
jruby.home: classpath:/META-INF/jruby.home
--- Context Init Parameters:
com.sun.faces.forceLoadConfiguration = true
com.sun.faces.validateXml = true
public.root = /
rails.env = production
--- Backtrace
NameError: uninitialized constant ApplicationController::SessionsHelper
--- RubyGems
Gem.dir: /opt/glassfish3/glassfish/domains/myDomain/applications/web-admin/WEB-INF/gems
Gem.path:
/opt/glassfish3/glassfish/domains/myDomain/applications/web-admin/WEB-INF/gems
Activated gems:
bundler-1.3.5
rake-10.0.4
i18n-0.6.1
multi_json-1.7.4
activesupport-3.2.13
builder-3.0.4
activemodel-3.2.13
erubis-2.7.0
journey-1.0.4
rack-1.4.5
rack-cache-1.2
rack-test-0.6.2
hike-1.2.2
tilt-1.4.1
sprockets-2.2.2
actionpack-3.2.13
mime-types-1.23
polyglot-0.3.3
treetop-1.4.12
mail-2.5.4
actionmailer-3.2.13
arel-3.0.2
tzinfo-0.3.37
activerecord-3.2.13
activeresource-3.2.13
gyoku-1.0.0
nokogiri-1.5.9-java
akami-1.2.0
bcrypt-ruby-3.0.1-java
sass-3.2.9
bootstrap-sass-2.3.1.2
will_paginate-3.0.4
bootstrap-will_paginate-0.0.9
bouncy-castle-java-1.5.0147
coffee-script-source-1.6.2
execjs-1.4.0
coffee-script-2.2.0
rack-ssl-1.3.3
json-1.8.0-java
rdoc-3.12.2
thor-0.18.1
railties-3.2.13
coffee-rails-3.2.2
faker-1.1.2
httpi-2.0.2
jquery-rails-2.2.2
jruby-openssl-0.8.8
nori-2.1.0
rails-3.2.13
sass-rails-3.2.6
wasabi-3.1.0
savon-2.2.0
therubyrhino_jar-1.7.4
therubyrhino-2.0.2
uglifier-1.0.4
uuidtools-2.1.4
--- Bundler
Bundler.bundle_path: /opt/glassfish3/glassfish/domains/myDomain/applications/web-admin/WEB-INF/gems
Bundler.root: /opt/glassfish3/glassfish/domains/myDomain/applications/web-admin/WEB-INF
Gemfile: /opt/glassfish3/glassfish/domains/myDomain/applications/web-admin/WEB-INF/Gemfile
Settings:
gemfile = /opt/glassfish3/glassfish/domains/myDomain/applications/web-admin/WEB-INF/Gemfile
without = development:test:assets
bin_path = /opt/glassfish3/glassfish/domains/myDomain/applications/web-admin/WEB-INF/gems/gems/bundler-1.3.5/bin/bundle
--- JRuby-Rack Config
compat_version =
default_logger = org.jruby.rack.logging.StandardOutLogger#62a49a04
equals =
err = com.sun.common.util.logging.LoggingOutputStream$LoggingPrintStream#7a21bdb8
filter_adds_html = true
filter_verifies_resource = false
ignore_environment = false
initial_memory_buffer_size =
initial_runtimes =
jms_connection_factory =
jms_jndi_properties =
logger = org.jruby.rack.logging.ServletContextLogger#19a2312c
logger_class_name = servlet_context
logger_name = jruby.rack
maximum_memory_buffer_size =
maximum_runtimes =
num_initializer_threads =
out = com.sun.common.util.logging.LoggingOutputStream$LoggingPrintStream#52f8d395
rackup =
rackup_path =
rewindable = true
runtime_arguments =
runtime_environment =
runtime_timeout_seconds =
serial_initialization = false
servlet_context = org.apache.catalina.core.ApplicationContextFacade#16c7e149
throw_init_exception = false
|#]
[#|2013-05-31T17:10:25.182-0400|INFO|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=19;_ThreadName=Thread-2;|PWC1412: WebModule[null] ServletContext.log():DEBUG: resetting rack response due exception|#]
Turns out it was an issue with source code control. My helpers directory was not added and therefore Jenkins was not including in the build. Always check the obvious first, if it says it isn't there it probably isn't.