Connect to a SQL database

Configurare noua (How To)

Situatie

This code creates a new SQL database with a firewall rule allowing remote access, and then connected to it using the Microsoft ODBC driver. Pyodbc uses the Microsoft ODBC Driver on Linux to connect to SQL Databases.

Solutie

Authenticate:

azcli

az login

Create a resource group:

Azure CLI
az group create -l eastus -n azure-sample-group
Create a SQL server:
Azure CLI
az sql server create –admin-password HusH_Sec4et –admin-user mysecretname -l eastus -n samplesqlserver123 -g azure-sample-group
Add firewall rule:
Azure CLI
az sql server firewall-rule create –end-ip-address 167.220.0.235 –name firewall_rule_name_123.123.123.123 –resource-group azure-sample-group –server samplesqlserver123 –start-ip-address 123.123.123.123
Create a SQL database:
Azure CLI
az sql db create –name sample-db –resource-group azure-sample-group –server samplesqlserver123
Python

from azure.mgmt.sql import SqlManagementClient
from azure.common.client_factory import get_client_from_cli_profile
import pyodbc

LOCATION = ‘eastus’
GROUP_NAME = ‘azure-sample-group’
SERVER_NAME = ‘samplesqlserver123’
DATABASE_NAME = ‘sample-db’
USER_NAME =’mysecretname’
PASSWORD=’HusH_Sec4et’

# authenticate
sql_client = get_client_from_cli_profile(SqlManagementClient)

def run_example():
# Get SQL database
print(‘Get SQL database’)
database = sql_client.databases.get(
GROUP_NAME,
SERVER_NAME,
DATABASE_NAME
)
print(database)
print(“nn”)

def create_and_insert():
server = SERVER_NAME+’.database.windows.net’
database = DATABASE_NAME
username = USER_NAME
password = PASSWORD
driver = ‘{ODBC Driver 13 for SQL Server}’
cnxn = pyodbc.connect(
‘DRIVER=’ + driver + ‘;PORT=1433;SERVER=’ + server + ‘;PORT=1443;DATABASE=’ + database + ‘;UID=’ + username + ‘;PWD=’ + password)
cursor = cnxn.cursor()
tsql = “CREATE TABLE CLOUD (name varchar(255), code int);”
tsqlInsert = “INSERT INTO CLOUD (name, code) VALUES (‘Azure’, 1); ”
selectValues = “SELECT * FROM CLOUD”
with cursor.execute(tsql):
print(‘Successfully created table!’)
with cursor.execute(tsqlInsert):
print(‘Successfully inserted data into table’)
cursor.execute(selectValues)
row = cursor.fetchone()
while row:
print(str(row[0]) + ” ” + str(row[1]))
row = cursor.fetchone()
cnxn.commit()

if __name__ == “__main__”:
run_example()
create_and_insert()

Once you’ve verified that the code worked, use the CLI to delete the SQL database and its resources.

Azure CLI

az group delete –name azure-sample-group

Tip solutie

Permanent

Voteaza

(12 din 34 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?