Python – PyMySql MySql 활용

Python – PyMySQL

MySQL Download

https://www.mysql.com/downloads/

MySQL Client

MySQL Workbench

https://dev.mysql.com/downloads/workbench/

phpMyAdmin – AutoSet Download

Python 에서 MySql 연결

PyMySQL

https://pymysql.readthedocs.io/en/latest/

PyMySQL 모듈 설치

pip install PyMySQL

Step 0: Create Table

  • mysql client로 서버 접속
CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `email` varchar(255) COLLATE utf8_bin NOT NULL,
    `password` varchar(255) COLLATE utf8_bin NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;

Python에서 pymysql 사용하는 일반적인 절차

  • pymysql 모듈을 import
  • pymysql.connect() 메소드를 사용하여 MYSQL에 Connect
  • 호스트명, 로그인, 암호, 접속할 DB 등을 파라미터로 지정
  • DB 접속이 성공하면, Connection 객체로부터 cursor() 메서드를 호출
  • Cursor 객체의 메서드를 통해 MYSQL 서버와 작업 관리
  • Cursor 객체의 execute() 메서드를 사용하여 SQL 문장을 DB 서버로 전송
  • SQL 쿼리의 경우 Cursor 객체의 fetchall(), fetchone(), fetchmany() 등의 메서드를 사용
  • 데이타를 서버로부터 가져온 후, Fetch 된 데이타를 사용
  • Insert, Update, Delete 등의 DML(Data Manipulation Language) 문장을 실행
  • Connection 객체 commit() 은 실제로 DML 문장을 서버에 실제 실행
  • Connection 객체 rollback() 실행 으로 DML 문장 취소
  • Connection 객체의 close() 메서드를 사용하여 DB 연결 닫기

Step 1: Connect

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='password', db='test')

Step 2: Execute query

fetchone

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='password', db='test')

try:
    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` "
        #sql = "SELECT `id`, `password` FROM `users` WHERE `id`=%s"
        cursor.execute(sql)
        #cursor.execute(sql, ('1',))
        rows = cursor.fetchone()
        for row in rows:
            print(row)
finally:
    connection.close()

fetchall

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='password', db='test')

try:
    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` "        
        cursor.execute(sql)
        rows = cursor.fetchall()
        for row in rows:
            print(row)
finally:
    connection.close()

Step 3: Insert a row

import pymysql

conn = pymysql.connect(host='localhost', user='root', password='password', db='test')

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다