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

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!

Related

Running database migrations during Google Cloud Build fails with ENOTFOUND error

I am trying to run migrations through Sequelize in Node JS on Google Cloud Run connecting to a MySQL Google Cloud SQL database. I followed
https://stackoverflow.com/a/58441728/4487248 to get the Google Cloud proxy setup. Given this log setting up the proxy connection to the database seems to have worked:
Step #2 - "migrate": Already have image (with digest): gcr.io/cloud-builders/yarn
Step #2 - "migrate": 2021/10/02 14:19:58 current FDs rlimit set to 1048576, wanted limit is 8500. Nothing to do here.
Step #2 - "migrate": 2021/10/02 14:19:58 Listening on /workspace/<MY-INSTANCE-NAME> for <MY-INSTANCE-NAME>
Step #2 - "migrate": 2021/10/02 14:19:58 Ready for new connections
Step #2 - "migrate": 2021/10/02 14:19:58 Generated RSA key in 74.706896ms
However, when I try to run migrations with yarn knex migrate:latest or ./node_modules/.bin/sequelize db:migrate I run into:
getaddrinfo ENOTFOUND /workspace/<MY-INSTANCE-NAME>
This seems to imply that the host could not be found.
Output / Logs
My cloudbuild.yaml (composed of https://stackoverflow.com/a/52366671/4487248 & https://stackoverflow.com/a/58441728/4487248):
steps:
# Install Node.js dependencies
- id: yarn-install
name: gcr.io/cloud-builders/yarn
waitFor: ["-"]
# Install Cloud SQL proxy
- id: proxy-install
name: gcr.io/cloud-builders/yarn
entrypoint: sh
args:
- "-c"
- "wget https://storage.googleapis.com/cloudsql-proxy/v1.25.0/cloud_sql_proxy.linux.amd64 -O /workspace/cloud_sql_proxy && chmod +x /workspace/cloud_sql_proxy"
waitFor: ["-"]
- id: migrate
name: gcr.io/cloud-builders/yarn
entrypoint: sh
args:
- "-c"
- "(/workspace/cloud_sql_proxy -dir=/workspace -instances=<MY-INSTANCE-NAME> & sleep 2) && ./node_modules/.bin/sequelize db:migrate"
timeout: "1200s"
waitFor: ["yarn-install", "proxy-install"]
timeout: "1200s"
My .sequelizerc (Documentation here):
const path = require('path');
module.exports = {
'config': path.resolve('config', 'config.js')
}
My config/config.js:
module.exports = {
production: {
username: process.env.PROD_DB_USERNAME,
password: process.env.PROD_DB_PASSWORD,
database: process.env.PROD_DB_NAME,
host: `/workspace/${process.env.INSTANCE_CONNECTION_NAME}`, // Replacing this line with `/workspace/cloudsql/${..}` or `/cloudsql/${..}` leads to the same error
dialect: 'mysql',
}
}
I did enable Public IP on the MySQL instance:
Setting the host to localhost and adding the instance path in socketPath in config.js fixed the issue:
module.exports = {
production: {
username: process.env.PROD_DB_USERNAME,
password: process.env.PROD_DB_PASSWORD,
database: process.env.PROD_DB_NAME,
host: localhost,
dialect: 'mysql',
dialectOptions: {
socketPath: `/workspace/${process.env.INSTANCE_CONNECTION_NAME}`,
},
}
}

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.

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.

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.

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.