Python MySQL

Library

There are a lot of library for MySQL.

In Python3, PyMySQL is a bit good, I thought.

PyMySQL

Python
Github
Github link has easy description how to use it. It is useful guide to write program.

Install

PyMySQL is PyPI index. Try following if you have PyPI

pip install PyMySQL

Sample Program

import pymysql.cursors

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='',
                             db='sampledb')


try:
    with connection.cursor() as cursor:
        # CREATE TABLE
        sql = "CREATE TABLE IF NOT EXISTS items(id int, name varchar(100), price int);"
        cursor.execute(sql)
    connection.commit()

    # Insert
    with connection.cursor() as cursor:
        sql = "INSERT INTO `items` (`id`, `name`, `price`) VALUES (%s, %s, %s)"
        cursor.execute(sql, ('2', 'ABC', '200'))
    connection.commit()

    # Select

    with connection.cursor() as cursor:
        # Read
        sql = "SELECT * FROM `items`;"
        cursor.execute(sql)
        for row in cursor:
            print(row)

finally:
    connection.close()