快速入门:使用 Python 连接到 Azure Database for MySQL 并查询其中的数据

适用于:Azure Database for MySQL - 单一服务器

重要

Azure Database for MySQL 单一服务器即将停用。 强烈建议升级到 Azure Database for MySQL 灵活服务器。 有关如何迁移到 Azure Database for MySQL 灵活服务器的详细信息,请参阅 Azure Database for MySQL 单一服务器发生了什么情况?

在本快速入门中,你将使用 Python 连接到 Azure Database for MySQL。 然后使用 SQL 语句在 Mac、Ubuntu Linux 和 Windows 平台的数据库中查询、插入、更新和删除数据。

先决条件

对于本快速入门,你需要:

安装 Python 和 MySQL 连接器

使用以下步骤在计算机上安装 Python 和用于 Python 的 MySQL 连接器:

注意

本快速入门使用 MySQL 连接器/Python 开发人员指南

  1. 下载并安装适合自己 OS 的 Python 3.7 或更高版本。 请确保将 Python 添加到 PATH,因为 MySQL 连接器需要它。

  2. 打开命令提示符或 bash shell,使用大写 V 开关运行 python -V,以便检查 Python 版本。

  3. 最新版本的 Python 中包含 pip 包安装程序。 通过运行 pip install -U pippip 更新为最新版本。

    如果未安装 pip,则可使用 get-pip.py 下载并安装它。 有关详细信息,请参阅安装

  4. 使用 pip,安装用于 Python 的 MySQL 连接器及其依赖项:

    pip install mysql-connector-python
    

获取连接信息

从 Azure 门户获取连接到 Azure Database for MySQL 所需的连接信息。 需要服务器名称、数据库名称和登录凭据。

  1. 登录 Azure 门户

  2. 在门户搜索栏中,搜索并选择创建的 Azure Database for MySQL 服务器,如 mydemoserver

    Azure Database for MySQL 服务器名称

  3. 从服务器的“概览”页中记下“服务器名称”和“服务器管理员登录名”。 如果忘记了密码,也可通过此页重置密码。

    Azure Database for MySQL 服务器名称 2

运行 Python 代码示例

对于本文中的每个代码示例:

  1. 在文本编辑器中创建新的文件。

  2. 将代码示例添加到文件。 在代码中,将 <mydemoserver><myadmin><mypassword><mydatabase> 占位符替换为 MySQL 服务器和数据库的值。

  3. Azure Database for MySQL 服务器默认启用 SSL。 从本地环境进行连接可能需要下载 DigiCertGlobalRootCA SSL 证书。 将代码中的 ssl_ca 值替换为指向计算机上此文件的路径。

  4. 将文件保存在项目文件夹中,扩展名为 .py,例如 C:\pythonmysql\createtable.py/home/username/pythonmysql/createtable.py

  5. 若要运行代码,请打开命令提示符或 bash shell,将目录更改为项目文件夹,例如 cd pythonmysql。 键入 python 命令,后跟文件名,例如 python createtable.py,然后按 Enter。

    注意

    在 Windows 上,如果找不到 python.exe,则可能需要将 Python 路径添加到 PATH 环境变量中,或提供 python.exe 的完整路径,例如 C:\python27\python.exe createtable.py

步骤 1:创建表并插入数据

通过以下代码连接到服务器和数据库,创建一个表,然后使用 INSERT SQL 语句加载数据。此代码导入 mysql.connector 库,并使用以下方法:

import mysql.connector
from mysql.connector import errorcode

# Obtain connection string information from the portal

config = {
  'host':'<mydemoserver>.mysql.database.chinacloudapi.cn',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootCA.crt.pem'
}

# Construct connection string

try:
   conn = mysql.connector.connect(**config)
   print("Connection established")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with the user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cursor = conn.cursor()

  # Drop previous table of same name if one exists
  cursor.execute("DROP TABLE IF EXISTS inventory;")
  print("Finished dropping table (if existed).")

  # Create table
  cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
  print("Finished creating table.")

  # Insert some data into table
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("banana", 150))
  print("Inserted",cursor.rowcount,"row(s) of data.")
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("orange", 154))
  print("Inserted",cursor.rowcount,"row(s) of data.")
  cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("apple", 100))
  print("Inserted",cursor.rowcount,"row(s) of data.")

  # Cleanup
  conn.commit()
  cursor.close()
  conn.close()
  print("Done.")

步骤 2:读取数据

使用以下代码进行连接,并使用 SELECT SQL 语句读取数据。 该代码导入 mysql.connector 库,并使用 cursor.execute() 方法对 MySQL 数据库执行 SQL 查询。

代码使用 fetchall() 方法读取数据行,将结果集保留在集合行中,并使用 for 迭代器对行进行循环操作。

import mysql.connector
from mysql.connector import errorcode

# Obtain connection string information from the portal

config = {
  'host':'<mydemoserver>.mysql.database.chinacloudapi.cn',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootCA.crt.pem'
}

# Construct connection string

try:
   conn = mysql.connector.connect(**config)
   print("Connection established")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with the user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cursor = conn.cursor()

  # Read data
  cursor.execute("SELECT * FROM inventory;")
  rows = cursor.fetchall()
  print("Read",cursor.rowcount,"row(s) of data.")

  # Print all rows
  for row in rows:
  	print("Data row = (%s, %s, %s)" %(str(row[0]), str(row[1]), str(row[2])))

  # Cleanup
  conn.commit()
  cursor.close()
  conn.close()
  print("Done.")

步骤 3:更新数据

使用以下代码进行连接,并使用 UPDATE SQL 语句更新数据。 该代码导入 mysql.connector 库,并使用 cursor.execute() 方法对 MySQL 数据库执行 SQL 查询。

import mysql.connector
from mysql.connector import errorcode

# Obtain connection string information from the portal

config = {
  'host':'<mydemoserver>.mysql.database.chinacloudapi.cn',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootCA.crt.pem'
}

# Construct connection string

try:
   conn = mysql.connector.connect(**config)
   print("Connection established")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with the user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cursor = conn.cursor()

  # Update a data row in the table
  cursor.execute("UPDATE inventory SET quantity = %s WHERE name = %s;", (300, "apple"))
  print("Updated",cursor.rowcount,"row(s) of data.")

  # Cleanup
  conn.commit()
  cursor.close()
  conn.close()
  print("Done.")

步骤 4:删除数据

使用以下代码进行连接,并使用 DELETE SQL 语句删除数据。 该代码导入 mysql.connector 库,并使用 cursor.execute() 方法对 MySQL 数据库执行 SQL 查询。

import mysql.connector
from mysql.connector import errorcode

# Obtain connection string information from the portal

config = {
  'host':'<mydemoserver>.mysql.database.chinacloudapi.cn',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootCA.crt.pem'
}

# Construct connection string

try:
   conn = mysql.connector.connect(**config)
   print("Connection established")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with the user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cursor = conn.cursor()

  # Delete a data row in the table
  cursor.execute("DELETE FROM inventory WHERE name=%(param1)s;", {'param1':"orange"})
  print("Deleted",cursor.rowcount,"row(s) of data.")
  
  # Cleanup
  conn.commit()
  cursor.close()
  conn.close()
  print("Done.")  

清理资源

若要清理本快速入门中使用的所有资源,请使用以下命令删除该资源组:

az group delete \
    --name $AZ_RESOURCE_GROUP \
    --yes

后续步骤