🤖 Ai回答: To work with MySQL in Ruby, you typically use the `mysql2` gem — which is the modern, recommended gem for connecting to MySQL databases from Ruby applications (especially for Rails and non-Rails projects).
✅ Step-by-Step: Using MySQL in Ruby
1、Add the Gem to Your Project
If you're using Bundler (Rails or non-Rails), add this to your `Gemfile`:
ruby
gem 'mysql2'
Then run:
bash
bundle install
⚠️ Note: If you’re on macOS and have issues installing `mysql2`, you might need to install MySQL via Homebrew first:
bash
brew install mysql@8.0
And then set the `MYSQL2_LIB_DIR` and `MYSQL2_INCLUDE_DIR` if needed.
2、Basic Connection Example
Here’s a simple Ruby script that connects to MySQL and runs a query:
ruby
require 'mysql2'
Connect to MySQL
client = Mysql2::Client.new(
host: 'localhost',
username: 'your_username',
password: 'your_password',
database: 'your_database_name',
port: 3306
)
Execute a query
results = client.query(SELECT * FROM users)
Print results
results.each do |row|
puts row
end
Close connection
client.close
💡 You can also use `begin...rescue...end` blocks for error handling.
3、Using Prepared Statements (Safe from SQL Injection)
ruby
client = Mysql2::Client.new(...)
Use prepared statement
stmt = client.prepare(SELECT name FROM users WHERE id = ?)
result = stmt.execute(5)
result.each do |row|
puts row['name']
end
stmt.close
4、Error Handling
ruby
begin
client = Mysql2::Client.new(...)
result = client.query(SELECT * FROM non_existent_table)
rescue Mysql2::Error = e
puts Database error: {e.message}
ensure
client&.close
end
5、With ActiveRecord (if using Rails)
If you’re in a Rails app, you don’t need to manually connect — Rails configures it automatically via `config/database.yml`.
You can test your connection with a simple Ruby script:
ruby
require 'mysql2'
begin
client = Mysql2::Client.new(
host: 'localhost',
username: 'root',
password: '',
database: 'test_db'
)
puts Connected successfully!
client.close
rescue = e
puts Failed: {e.message}
end
📌 Best Practices
Always use prepared statements to avoid SQL injection.
Never hardcode passwords — use environment variables (`ENV['DB_PASSWORD']`).
Use connection pooling in production apps (e.g., via `connection_pool` gem).
Consider using `ActiveRecord` if you’re building a web app (Rails or otherwise).
🧩 Alternative: `pg` for PostgreSQL
If you ever need to switch to PostgreSQL, use `pg` gem instead:
ruby
gem 'pg'
But for MySQL → stick with `mysql2`.
📚 Resources
[mysql2 GitHub](https://github.com/brianmario/mysql2)
[Mysql2 Docs](https://www.rubydoc.info/gems/mysql2/)
[Ruby on Rails Database Configuration](https://guides.rubyonrails.org/configuring.htmlconfiguring-a-database)
Let me know if you want help setting up a full Rails app with MySQL, or connecting to a remote database, or writing migrations! 😊