Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

Python의 MySqldb 연결

<시간/>

MySQL은 가장 널리 사용되는 오픈 소스 DB 중 하나입니다. Python은 이 DB에 연결하고 DB를 사용하여 데이터를 저장하고 검색하는 방법을 제공합니다.

pymysql 설치

사용하는 python 환경에 따라 다음 방법 중 하나로 pymysql 패키지를 설치할 수 있습니다.

# From python console
pip install pymysql
#Using Anaconda
conda install -c anaconda pymysql
# Add modules using any python IDE
pymysql

MySql에 연결

이제 다음 코드를 사용하여 MySQL 환경에 연결할 수 있습니다. 접속 후 DB의 버전을 알아냅니다.

예시

import pymysql
# Open database connection
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)

# disconnect from server
db.close()

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Database version : 8.0.19

DB 명령어 실행

DB 명령을 실행하기 위해 db 커서와 해당 커서에 전달할 SQL 쿼리를 생성합니다. 그런 다음 cursor.execute 메소드를 사용하여 커서 실행 결과를 가져옵니다.

예시

import pymysql
# Open database connection
db = pymysql.connect("localhost","username","paswd","DBname" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql = "SELECT * FROM EMPLOYEE \
      WHERE INCOME > '%d'" % (1000)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      # Now print fetched result
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
            (fname, lname, age, sex, income )
except:
   print "Error: unable to fecth data"
# disconnect from server
db.close()
에서

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

fname = Jack, lname = Ma, age = 31, sex = M, income = 12000