Python MySQL

PyMySQL


PyMySQL 모듈 설치


Step 0: Create Table


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 사용하는 일반적인 절차


Step 1: Connect


import pymysql

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

Step 2: Execute query


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()
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()