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:
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
Leave A Comment?