빠른 시작: Python을 사용하여 Azure Database for MySQL에서 데이터 연결 및 쿼리

적용 대상: Azure Database for MySQL - 단일 서버

Important

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 이상을 다운로드하여 설치합니다. MySQL 커넥터를 사용하려면 PATH에 Python을 추가해야 합니다.

  2. 명령 프롬프트 또는 bash 셸을 열고 대문자 V 스위치를 사용하여 python -V를 실행하여 Python 버전을 확인합니다.

  3. pip 패키지 설치 관리자는 최신 버전의 Python에 포함되어 있습니다. pip install -U pip를 실행하여 최신 버전으로 pip를 업데이트합니다.

    pip가 설치되지 않은 경우 get-pip.py를 사용하여 다운로드하고 설치할 수 있습니다. 자세한 내용은 설치를 참조하세요.

  4. pip를 사용하여 Python용 MySQL 커넥터 및 해당 종속성을 설치합니다.

    pip install mysql-connector-python
    

연결 정보 가져오기

Azure Portal에서 Azure Database for MySQL에 연결하는 데 필요한 연결 정보를 가져옵니다. 서버 이름, 데이터베이스 이름 및 로그인 자격 증명이 필요합니다.

  1. Azure Portal에 로그인합니다.

  2. 포털 검색 창에서 mydemoserver와 같이 만든 Azure Database for MySQL 서버를 검색하여 선택합니다.

    Azure Database for MySQL server name

  3. 서버의 개요 패널에 있는 서버 이름서버 관리자 로그인 이름을 기록해 둡니다. 암호를 잊어버리면 이 페이지에서 암호를 재설정할 수 있습니다.

    Azure Database for MySQL server name 2

Python 코드 샘플 실행

이 문서의 각 코드 예제는 다음과 같습니다.

  1. 텍스트 편집기에서 새 파일을 만듭니다.

  2. 파일에 코드 예제를 추가합니다. 코드에서 <mydemoserver>, <myadmin>, <mypassword><mydatabase> 자리 표시자를 MySQL 서버 및 데이터베이스의 값으로 바꿉니다.

  3. SSL은 Azure Database for MySQL 서버에서 기본적으로 사용하도록 설정됩니다. 로컬 환경에서 연결하려면 DigiCertGlobalRootG2 SSL 인증서를 다운로드해야 할 수도 있습니다. 코드의 ssl_ca 값을 컴퓨터에 있는 이 파일의 경로로 바꿉니다.

  4. 파일을 C:\pythonmysql\createtable.py 또는 /home/username/pythonmysql/createtable.py와 같이 .py 파일 확장명이 포함된 프로젝트 폴더에 저장합니다.

  5. 코드를 실행하려면 명령 프롬프트 또는 bash 셸을 시작한 후 디렉터리를 사용자의 프로젝트 폴더로 변경합니다(예: cd pythonmysql). python 명령 다음에 파일 이름을 입력하고(예: python createtable.py) Enter 키를 누릅니다.

    참고 항목

    Windows에서 python.exe를 찾을 수 없으면 PATH 환경 변수에 Python 경로를 추가하거나 python.exe에 대한 전체 경로(예: C:\python27\python.exe createtable.py)를 제공해야 할 수 있습니다.

1단계: 테이블 만들기 및 데이터 삽입

다음 코드를 사용하여 서버 및 데이터베이스에 연결하고, 테이블을 만들고, INSERT SQL 문을 사용하여 데이터를 로드합니다. 이 코드는 mysql.connector 라이브러리를 가져오고 다음 메서드를 사용합니다.

  • 구성 컬렉션의 인수를 사용하여 Azure Database for MySQL에 연결하는 connect() 함수.
  • cursor.execute 메서드는 MySQL 데이터베이스에 대해 SQL 쿼리를 실행합니다.
  • 커서 사용을 마쳤을 경우 cursor.close().
  • conn.close(): 연결을 닫습니다.
import mysql.connector
from mysql.connector import errorcode

# Obtain connection string information from the portal

config = {
  'host':'<mydemoserver>.mysql.database.azure.com',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.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.azure.com',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.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.azure.com',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.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.azure.com',
  'user':'<myadmin>@<mydemoserver>',
  'password':'<mypassword>',
  'database':'<mydatabase>',
  'client_flags': [mysql.connector.ClientFlag.SSL],
  'ssl_ca': '<path-to-SSL-cert>/DigiCertGlobalRootG2.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

다음 단계