问题描述
- windows环境下,ruby 连接mysql 报错
-
require "D:/ruby-mysql/ruby-mysql-0.2.6/mysql"
begin
#尝试连接mysql数据库
my = Mysql.connect("localhost","root","123456","test")
#连接成功,显示Mysql数据库版本
puts my.get_server_info
rescue Mysql::Error => err
#如果失败,显示错误信息
puts "错误代码:#{err.errno}"
puts "错误信息:#{err.error}"
ensure
my.close if my
end运行以上代码,报这样的错误:
D:/ruby-mysql/ruby-mysql-0.2.6/mysql.rb:1019:inread': Packets out of order: 0<> (RuntimeError)
read'
from D:/ruby-mysql/ruby-mysql-0.2.6/mysql.rb:444:in
from D:/ruby-mysql/ruby-mysql-0.2.6/mysql.rb:110:inreal_connect'
initialize'
from D:/ruby-mysql/ruby-mysql-0.2.6/mysql.rb:91:in
from D:/ruby-mysql/ruby-mysql-0.2.6/mysql.rb:1085:innew'
real_connect'
from D:/ruby-mysql/ruby-mysql-0.2.6/mysql.rb:1085:in
from D:/软件/eclipse-standard-kepler-SR2-win32/hello/testDb.rb:3:in `'项目要用到ruby,新人,求大神帮忙,搞了一天了,没连上
解决方案
目测是你的musql端口没有指定对,或者mysql没有启动正确。或者被防火墙拦住了。
解决方案二:
参考brianmario/mysql2,你的MySQL的版本是多少?从MySQL 5.6.5开始,默认启用secure_auth
Secure auth
Starting wih MySQL 5.6.5, secure_auth is enabled by default on servers (it was disabled by default prior to this). When secure_auth is enabled, the server will refuse a connection if the account password is stored in old pre-MySQL 4.1 format. The MySQL 5.6.5 client library may also refuse to attempt a connection if provided an older format password. To bypass this restriction in the client, pass the option :secure_auth => false to Mysql2::Client.new(). If using ActiveRecord, your database.yml might look something like this:
development:
adapter: mysql2
encoding: utf8
database: my_db_name
username: root
password: my_password
host: 127.0.0.1
port: 3306
secure_auth: false
解决方案三:
不要用mysql ,用mysql2 adapter 试试.
gem install mysql2
require "rubygems"
require "active_record"
class Source < ActiveRecord::Base
set_table_name "sources"
ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:username => "test",
:password => "test",
:port => 3306,
:database => "TestDB",
:socket => "mysql"
)
end
source = Source.find(:first, :conditions => [ "source_id = ?", 2 ])
puts source.source_name