linux ruby mysql_快速入门:使用 Ruby 进行连接 - Azure Database for MySQL | Microsoft Docs

本文介绍如何在Windows、Ubuntu Linux和Mac平台上使用Ruby应用程序和mysql2 gem连接到Azure Database for MySQL。文中提供了详细的步骤说明如何安装Ruby及必要的库,并展示了如何使用SQL语句执行查询、插入、更新和删除操作。

您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用 Ruby 连接到 Azure Database for MySQL 并查询其中的数据Quickstart: Use Ruby to connect and query data in Azure Database for MySQL

5/26/2020

本文内容

本快速入门演示如何在 Windows、Ubuntu Linux 和 Mac 平台中使用 Ruby 应用程序和 mysql2 gem 连接到适用于 MySQL 的 Azure 数据库。This quickstart demonstrates how to connect to an Azure Database for MySQL using a Ruby application and the mysql2 gem from Windows, Ubuntu Linux, and Mac platforms. 同时还介绍了如何使用 SQL 语句在数据库中查询、插入、更新和删除数据。It shows how to use SQL statements to query, insert, update, and delete data in the database. 本主题假设你熟悉如何使用 Ruby 进行开发,但不太熟悉 Azure Database for MySQL 的用法。This topic assumes that you are familiar with development using Ruby and that you are new to working with Azure Database for MySQL.

先决条件Prerequisites

此快速入门使用以下任意指南中创建的资源作为起点:This quickstart uses the resources created in either of these guides as a starting point:

重要

确保已使用 Azure 门户或 Azure CLI 将服务器的防火墙规则添加到连接的 IP 地址Ensure the IP address you're connecting from has been added the server's firewall rules using the Azure portal or Azure CLI

安装 RubyInstall Ruby

在自己的计算机上安装 Ruby、Gem 和 MySQL2 库。Install Ruby, Gem, and the MySQL2 library on your own computer.

WindowsWindows

下载并安装 Ruby 版本 2.3。Download and Install the 2.3 version of Ruby.

从“开始”菜单启动新的命令提示符 (cmd)。Launch a new command prompt (cmd) from the Start menu.

将目录切换到 Ruby 版本 2.3 所在的目录。Change directory into the Ruby directory for version 2.3. cd c:\Ruby23-x64\bin

运行 ruby -v 命令查看所安装的版本,以测试 Ruby 安装。Test the Ruby installation by running the command ruby -v to see the version installed.

运行 gem -v 命令查看所安装的版本,以测试 Gem 安装。Test the Gem installation by running the command gem -v to see the version installed.

运行命令 gem install mysql2,使用 Gem 生成适用于 Ruby 的 Mysql2 模块。Build the Mysql2 module for Ruby using Gem by running the command gem install mysql2.

macOSmacOS

运行命令 brew install ruby,使用 Homebrew 安装 Ruby。Install Ruby using Homebrew by running the command brew install ruby. 如需更多安装选项,请参阅 Ruby 安装文档。For more installation options, see the Ruby installation documentation.

运行 ruby -v 命令查看所安装的版本,以测试 Ruby 安装。Test the Ruby installation by running the command ruby -v to see the version installed.

运行 gem -v 命令查看所安装的版本,以测试 Gem 安装。Test the Gem installation by running the command gem -v to see the version installed.

运行命令 gem install mysql2,使用 Gem 生成适用于 Ruby 的 Mysql2 模块。Build the Mysql2 module for Ruby using Gem by running the command gem install mysql2.

Linux (Ubuntu)Linux (Ubuntu)

通过运行命令 sudo apt-get install ruby-full 安装 Ruby。Install Ruby by running the command sudo apt-get install ruby-full. 如需更多安装选项,请参阅 Ruby 安装文档。For more installation options, see the Ruby installation documentation.

运行 ruby -v 命令查看所安装的版本,以测试 Ruby 安装。Test the Ruby installation by running the command ruby -v to see the version installed.

通过运行命令 sudo gem update --system 安装 Gem 的最新更新。Install the latest updates for Gem by running the command sudo gem update --system.

运行 gem -v 命令查看所安装的版本,以测试 Gem 安装。Test the Gem installation by running the command gem -v to see the version installed.

通过运行命令 sudo apt-get install build-essential 安装 gcc、make 和其他生成工具。Install the gcc, make, and other build tools by running the command sudo apt-get install build-essential.

运行 sudo apt-get install libmysqlclient-dev 命令安装 MySQL 客户端开发人员库。Install the MySQL client developer libraries by running the command sudo apt-get install libmysqlclient-dev.

运行命令 sudo gem install mysql2,使用 Gem 生成适用于 Ruby 的 mysql2 模块。Build the mysql2 module for Ruby using Gem by running the command sudo gem install mysql2.

获取连接信息Get connection information

获取连接到 Azure Database for MySQL 所需的连接信息。Get the connection information needed to connect to the Azure Database for MySQL. 需要完全限定的服务器名称和登录凭据。You need the fully qualified server name and login credentials.

在 Azure 门户的左侧菜单中,单击“所有资源”,然后搜索已创建的服务器(例如 mydemoserver)。From the left-hand menu in Azure portal, click All resources, and then search for the server you have created (such as mydemoserver).

单击服务器名称。Click the server name.

从服务器的“概览”面板中记下“服务器名称”和“服务器管理员登录名”。From the server's Overview panel, make a note of the Server name and Server admin login name. 如果忘记了密码,也可通过此面板来重置密码。If you forget your password, you can also reset the password from this panel.

ebc628e8b5146fde957e85ec79d7daba.png

运行 Ruby 代码Run Ruby code

将以下部分中的 Ruby 代码粘贴到文本文件,然后使用文件扩展名 .rb 将这些文件保存到项目文件夹中(例如 C:\rubymysql\createtable.rb 或 /home/username/rubymysql/createtable.rb)。Paste the Ruby code from the sections below into text files, and then save the files into a project folder with file extension .rb (such as C:\rubymysql\createtable.rb or /home/username/rubymysql/createtable.rb).

若要运行此代码,请启动命令提示符或 Bash shell。To run the code, launch the command prompt or Bash shell. 将目录切换到项目文件夹 cd rubymysqlChange directory into your project folder cd rubymysql

然后键入 Ruby 命令并后接文件名(例如 ruby createtable.rb)以运行应用程序。Then type the Ruby command followed by the file name, such as ruby createtable.rb to run the application.

在 Windows OS 上,如果 Ruby 应用程序不在路径环境变量中,则可能需要使用完整路径来启动 Node 应用程序,例如 "c:\Ruby23-x64\bin\ruby.exe" createtable.rbOn the Windows OS, if the Ruby application is not in your path environment variable, you may need to use the full path to launch the node application, such as "c:\Ruby23-x64\bin\ruby.exe" createtable.rb

进行连接并创建表Connect and create a table

使用以下代码进行连接,使用 CREATE TABLE SQL 语句创建表,然后使用 INSERT INTO SQL 语句将行添加到表中。Use the following code to connect and create a table by using CREATE TABLE SQL statement, followed by INSERT INTO SQL statements to add rows into the table.

该代码使用 mysql2::client 类连接到 MySQL 服务器。The code uses a mysql2::client class to connect to MySQL server. 然后调用 query() 方法,以便运行 DROP、CREATE TABLE 和 INSERT INTO 命令。Then it calls method query() to run the DROP, CREATE TABLE, and INSERT INTO commands. 最后,调用 close() 以在终止之前关闭连接。Finally, call the close() to close the connection before terminating.

将 host、database、username 和 password 字符串替换为你自己的值。Replace the host, database, username, and password strings with your own values.

require 'mysql2'

begin

# Initialize connection variables.

host = String('mydemoserver.mysql.database.azure.com')

database = String('quickstartdb')

username = String('myadmin@mydemoserver')

password = String('yourpassword')

# Initialize connection object.

client = Mysql2::Client.new(:host => host, :username => username, :database => database, :password => password)

puts 'Successfully created connection to database.'

# Drop previous table of same name if one exists

client.query('DROP TABLE IF EXISTS inventory;')

puts 'Finished dropping table (if existed).'

# Drop previous table of same name if one exists.

client.query('CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);')

puts 'Finished creating table.'

# Insert some data into table.

client.query("INSERT INTO inventory VALUES(1, 'banana', 150)")

client.query("INSERT INTO inventory VALUES(2, 'orange', 154)")

client.query("INSERT INTO inventory VALUES(3, 'apple', 100)")

puts 'Inserted 3 rows of data.'

# Error handling

rescue Exception => e

puts e.message

# Cleanup

ensure

client.close if client

puts 'Done.'

end

读取数据Read data

使用以下代码进行连接,并使用 SELECT SQL 语句读取数据。Use the following code to connect and read the data by using a SELECT SQL statement.

该代码使用 mysql2::client 类通过 new() 方法连接到 Azure Database for MySQL。The code uses a mysql2::client class to connect to Azure Database for MySQL with new()method. 然后,该代码调用 query() 方法来运行 SELECT 命令。Then it calls method query() to run the SELECT commands. 然后,它会调用方法 close(),在终止之前关闭连接。Then it calls method close() to close the connection before terminating.

将 host、database、username 和 password 字符串替换为你自己的值。Replace the host, database, username, and password strings with your own values.

require 'mysql2'

begin

# Initialize connection variables.

host = String('mydemoserver.mysql.database.azure.com')

database = String('quickstartdb')

username = String('myadmin@mydemoserver')

password = String('yourpassword')

# Initialize connection object.

client = Mysql2::Client.new(:host => host, :username => username, :database => database, :password => password)

puts 'Successfully created connection to database.'

# Read data

resultSet = client.query('SELECT * from inventory;')

resultSet.each do |row|

puts 'Data row = (%s, %s, %s)' % [row['id'], row['name'], row['quantity']]

end

puts 'Read ' + resultSet.count.to_s + ' row(s).'

# Error handling

rescue Exception => e

puts e.message

# Cleanup

ensure

client.close if client

puts 'Done.'

end

更新数据Update data

使用以下代码进行连接,并使用 UPDATE SQL 语句更新数据。Use the following code to connect and update the data by using an UPDATE SQL statement.

该代码使用 mysql2::client 类的 .new() 方法连接到适用于 MySQL 的 Azure 数据库。The code uses a mysql2::client class .new() method to connect to Azure Database for MySQL. 然后,该代码调用 query() 方法来运行 UPDATE 命令。Then it calls method query() to run the UPDATE commands. 然后,它会调用方法 close(),在终止之前关闭连接。Then it calls method close() to close the connection before terminating.

将 host、database、username 和 password 字符串替换为你自己的值。Replace the host, database, username, and password strings with your own values.

require 'mysql2'

begin

# Initialize connection variables.

host = String('mydemoserver.mysql.database.azure.com')

database = String('quickstartdb')

username = String('myadmin@mydemoserver')

password = String('yourpassword')

# Initialize connection object.

client = Mysql2::Client.new(:host => host, :username => username, :database => database, :password => password)

puts 'Successfully created connection to database.'

# Update data

client.query('UPDATE inventory SET quantity = %d WHERE name = %s;' % [200, '\'banana\''])

puts 'Updated 1 row of data.'

# Error handling

rescue Exception => e

puts e.message

# Cleanup

ensure

client.close if client

puts 'Done.'

end

删除数据Delete data

使用以下代码进行连接,并使用 DELETE SQL 语句读取数据。Use the following code to connect and read the data by using a DELETE SQL statement.

该代码使用 mysql2::client 类连接到 MySQL 服务器,运行 DELETE 命令,然后关闭与服务器的连接。The code uses a mysql2::client class to connect to MySQL server, run the DELETE command and then close the connection to the server.

将 host、database、username 和 password 字符串替换为你自己的值。Replace the host, database, username, and password strings with your own values.

require 'mysql2'

begin

# Initialize connection variables.

host = String('mydemoserver.mysql.database.azure.com')

database = String('quickstartdb')

username = String('myadmin@mydemoserver')

password = String('yourpassword')

# Initialize connection object.

client = Mysql2::Client.new(:host => host, :username => username, :database => database, :password => password)

puts 'Successfully created connection to database.'

# Delete data

resultSet = client.query('DELETE FROM inventory WHERE name = %s;' % ['\'orange\''])

puts 'Deleted 1 row.'

# Error handling

rescue Exception => e

puts e.message

# Cleanup

ensure

client.close if client

puts 'Done.'

end

清理资源Clean up resources

若要清理本快速入门中使用的所有资源,请使用以下命令删除该资源组:To clean up all resources used during this quickstart, delete the resource group using the following command:

az group delete \

--name $AZ_RESOURCE_GROUP \

--yes

后续步骤Next steps

先展示下效果 https://pan.quark.cn/s/a4b39357ea24 遗传算法 - 简书 遗传算法的理论是根据达尔文进化论而设计出来的算法: 人类是朝着好的方向(最优解)进化,进化过程中,会自动选择优良基因,淘汰劣等基因。 遗传算法(英语:genetic algorithm (GA) )是计算数学中用于解决最佳化的搜索算法,是进化算法的一种。 进化算法最初是借鉴了进化生物学中的一些现象而发展起来的,这些现象包括遗传、突变、自然选择、杂交等。 搜索算法的共同特征为: 首先组成一组候选解 依据某些适应性条件测算这些候选解的适应度 根据适应度保留某些候选解,放弃其他候选解 对保留的候选解进行某些操作,生成新的候选解 遗传算法流程 遗传算法的一般步骤 my_fitness函数 评估每条染色体所对应个体的适应度 升序排列适应度评估值,选出 前 parent_number 个 个体作为 待选 parent 种群(适应度函数的值越小越好) 从 待选 parent 种群 中随机选择 2 个个体作为父方和母方。 抽取父母双方的染色体,进行交叉,产生 2 个子代。 (交叉概率) 对子代(parent + 生成的 child)的染色体进行变异。 (变异概率) 重复3,4,5步骤,直到新种群(parentnumber + childnumber)的产生。 循环以上步骤直至找到满意的解。 名词解释 交叉概率:两个个体进行交配的概率。 例如,交配概率为0.8,则80%的“夫妻”会生育后代。 变异概率:所有的基因中发生变异的占总体的比例。 GA函数 适应度函数 适应度函数由解决的问题决定。 举一个平方和的例子。 简单的平方和问题 求函数的最小值,其中每个变量的取值区间都是 [-1, ...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值