Editar

Partilhar via


Bibliotecas de PostgreSQL/MySQL do Azure para PythonAzure MySQL/PostgreSQL libraries for Python

MySQLMySQL

Trabalhar com recursos e dados armazenados no Banco de Dados MySQL do Azure a partir do Python com o gerenciador do MySQL e pyodbc.Work with resources and data stored in Azure MySQL Database from python with the MySQL manager and pyodbc.

Pyodbc e driver ODBC de clienteClient ODBC driver and pyodbc

A biblioteca de cliente recomendada para acessar o Banco de Dados do Azure para MySQL é o driver ODBC da Microsoft.The recommended client library for accessing Azure Database for MySQL is the Microsoft ODBC driver. Use o driver ODBC para se conectar ao banco de dados e executar instruções SQL diretamente.Use the ODBC driver to connect to the database and execute SQL statements directly.

ExemploExample

Conectar-se ao Banco de Dados do Azure para MySQL e selecionar todos os registros na tabela de vendas.Connect to a Azure Database for MySQL and select all records in the sales table. Você pode obter a cadeia de conexão de ODBC para o seu banco de dados a partir do portal do Azure.You can get the ODBC connection string for the database from the Azure Portal.

SERVER = 'YOUR_SEVER_NAME' + '.mysql.database.azure.com'
DATABASE = 'YOUR_DATABASE_NAME'
USERNAME = 'YOUR_MYSQL_USERNAME'
PASSWORD = 'YOUR_MYSQL_PASSWORD'

DRIVER = '{MySQL ODBC 5.3 UNICODE Driver}'
cnxn = pyodbc.connect(
    'DRIVER=' + DRIVER + ';PORT=3306;SERVER=' + SERVER + ';PORT=3306;DATABASE=' + DATABASE + ';UID=' + USERNAME + ';PWD=' + PASSWORD)
cursor = cnxn.cursor()
selectsql = "SELECT * FROM SALES"  # SALES is an example table name
cursor.execute(selectsql)

API de gerenciamentoManagement API

Criar e gerenciar recursos do MySQL na sua assinatura com a API de gerenciamento.Create and manage MySQL resources in your subscription with the management API.

RequisitosRequirements

Você deve instalar as bibliotecas de gerenciamento do MySQL para Python.You must install the MySQL management libraries for Python.

pip install azure-mgmt-rdbms

Consulte a página de autenticação do SDK de Python para obter detalhes sobre como obter credenciais para autenticar com o cliente de gerenciamento.Please see the Python SDK authentication page for details on obtaining credentials to authenticate with the management client.

ExemploExample

Criar um recurso de Banco de Dados MySQL 5.7 e restringir o acesso a um intervalo de endereços IP usando uma regra de firewall.Create a MySQL 5.7 Database resource and restrict access to a range of IP addresses using a firewall rule.


from azure.mgmt.rdbms.mysql import MySQLManagementClient
from azure.mgmt.rdbms.mysql.models import ServerForCreate, ServerPropertiesForDefaultCreate, ServerVersion

SUBSCRIPTION_ID = "YOUR_AZURE_SUBSCRIPTION_ID"
RESOURCE_GROUP = "YOUR_AZURE_RESOURCE-GROUP_WITH_POSTGRES"
MYSQL_SERVER = "YOUR_DESIRED_MYSQL_SERVER_NAME"
MYSQL_ADMIN_USER = "YOUR_MYSQL_ADMIN_USERNAME"
MYSQL_ADMIN_PASSWORD = "YOUR_MYSQL_ADMIN_PASSOWRD"
LOCATION = "westus"  # example Azure availability zone, should match resource group


client = MySQLManagementClient(credentials=creds,
    subscription_id=SUBSCRIPTION_ID)

server_creation_poller = client.servers.create_or_update(
    resource_group_name=RESOURCE_GROUP,
    server_name=MYSQL_SERVER,
    ServerForCreate(
        ServerPropertiesForDefaultCreate(
            administrator_login=MYSQL_ADMIN_USER,
            administrator_login_password=MYSQL_ADMIN_PASSWORD,
            version=ServerVersion.five_full_stop_seven
        ),
        location=LOCATION
    )
)

server = server_creation_poller.result()

# Open access to this server for IPs
rule_creation_poller = client.firewall_rules.create_or_update(
    RESOURCE_GROUP
    MYSQL_SERVER,
    "some_custom_ip_range_whitelist_rule_name",  # Custom firewall rule name
    "123.123.123.123",  # Start ip range
    "167.220.0.235"  # End ip range
)

firewall_rule = rule_creation_poller.result()

PostgreSQLPostgreSQL

Use o driver ODBC e o pyodbc para se conectar ao banco de dados e executar instruções SQL diretamente.Use the ODBC driver and pyodbc to connect to the database and execute SQL statements directly.

Saiba mais sobre o Banco de Dados do Azure para PostgreSQL.Learn more about Azure Database for PostgreSQL.

Pyodbc e driver ODBC de clienteClient ODBC driver and pyodbc

A biblioteca de clientes recomendada para acessar o Banco de Dados do Azure para PostgreSQL é o driver ODBC da Microsoft e o pyodbc.The recommended client library for accessing Azure Database for PostgreSQL is the Microsoft ODBC driver and pyodbc.

ExemploExample

Conectar-se ao Banco de Dados do Azure para PostgreSQL e selecionar todos os registros na tabela SALES.Connect to a Azure Database for PostgreSQL and select all records in the SALES table. Você pode obter a cadeia de conexão de ODBC para o seu banco de dados a partir do portal do Azure.You can get the ODBC connection string for the database from the Azure Portal.

import pyodbc

SERVER = 'YOUR_SERVER_NAME.postgres.database.azure.com'
DATABASE = 'YOUR_DB_NAME'
USERNAME = 'YOUR_USERNAME'
PASSWORD = 'YOUR_PASSWORD'

DRIVER = '{PostgreSQL ODBC Driver}'
cnxn = pyodbc.connect(
    'DRIVER=' + DRIVER + ';PORT=5432;SERVER=' + SERVER +
    ';PORT=5432;DATABASE=' + DATABASE + ';UID=' + USERNAME +
    ';PWD=' + PASSWORD)
cursor = cnxn.cursor()
selectsql = "SELECT * FROM SALES" # SALES is an example table name
cursor.execute(selectsql)

API de gerenciamentoManagement API

RequisitosRequirements

Você deve instalar as bibliotecas de gerenciamento do PostGreSQL para Python.You must install the PostgreSQL management libraries for Python.

pip install azure-mgmt-rdbms

Consulte a página de autenticação do SDK de Python para obter detalhes sobre como obter credenciais para autenticar com o cliente de gerenciamento.Please see the Python SDK authentication page for details on obtaining credentials to authenticate with the management client.

ExemploExample

Neste exemplo, criaremos um novo banco de dados Postgres em nosso servidor Postgres existente.In this example we will create a new Postgres database on our existing Postgres server.

from azure.mgmt.rdbms.postgresql import PostgreSQLManagementClient

SUBSCRIPTION_ID = "YOUR_AZURE_SUBSCRIPTION_ID"
RESOURCE_GROUP = "YOUR_AZURE_RESOURCE_GROUP_WITH_POSTGRES"
POSTGRES_SERVER = "YOUR_POSTGRES_SERVER_NAME"
DB_NAME = "YOUR_DESIRED_DATABASE_NAME"

client = PostgreSQLManagementClient(credentials, SUBSCRIPTION_ID)

db_creation_poller = client.databases.create_or_update(
    resource_group_name=RESOURCE_GROUP,
    server_name=POSTGRES_SERVER, database_name=DB_NAME)
db = db_creation_poller.result()