首先,请确保已经安装了 mysql2 gem:
gem install mysql2
接下来,可以使用以下代码连接到 MySQL 数据库、执行查询和获取结果:
require 'mysql2'
# 连接到 MySQL 数据库
client = Mysql2::Client.new(
host: "localhost",
username: "your_username",
password: "your_password",
database: "your_database"
)
puts "Connected to the MySQL database."
# 执行查询
query = "SELECT * FROM your_table"
results = client.query(query)
# 获取查询结果
results.each do |row|
puts row.inspect
end
# 插入数据
insert_query = "INSERT INTO your_table (column1, column2) VALUES (?, ?)"
client.query(insert_query, ["value1", "value2"])
# 更新数据
update_query = "UPDATE your_table SET column1 = ? WHERE column2 = ?"
client.query(update_query, ["new_value", "existing_value"])
# 删除数据
delete_query = "DELETE FROM your_table WHERE column = ?"
client.query(delete_query, ["value_to_delete"])
# 断开数据库连接
client.close
puts "Disconnected from the MySQL database."
请根据你的 MySQL 数据库设置,调整连接信息、查询语句和数据操作语句中的数据库、表名、列名等信息。这只是一个简单的教程,实际情况可能会根据不同的需求有所变化。如有其他问题,请随时提问。
转载请注明出处:http://www.zyzy.cn/article/detail/13444/Ruby