PythonでMySQLに接続、INSERT、SELECTしてみる

接続するパッケージはいろいろありそうな感じでしたが、
mysql-connector-pythonが公式っぽかったので、こちらで進めることにしました!

pip install mysql-connector-python

https://dev.mysql.com/doc/connector-python/en/
https://pypi.org/project/mysql-connector-python/

接続してみる

XAMPPで立てたMySQLに接続することができました!

import mysql.connector

cnx = mysql.connector.connect(
    user='root',
    password='',
    host='localhost',
    database='table_name'
)

if cnx.is_connected:
    print("Connected!")

https://dev.mysql.com/doc/connector-python/en/connector-python-tutorial-cursorbuffered.html
https://python.softmoco.com/basics/python-mysql-connect.php

INSERTしてみる

cur = cnx.cursor()

sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
cur.execute(sql, val)

cnx.commit()

https://www.w3schools.com/python/python_mysql_insert.asp

おまけ(こんな感じで使ったらわかりやすそう)

cur = cnx.cursor()

data = {
    'name' : 'John',
    'address' : 'Highway 21',
}

def insert(cursor, table_name, data):
    keys = ",".join(map(lambda k: '`'+k+'`', data.keys()))
    value_symbols = ",".join(['%s' for _ in range(len(data))])
    values = tuple(data.values())
    sql = "INSERT INTO " + table_name + " (" + keys + ") VALUES (" + value_symbols + ")"
    cursor.execute(sql, values)
    # IDの取得
    return cursor.lastrowid

id = insert(cur, 'customers', data)
print(id)

cnx.commit()

SELECTしてみる

cur = cnx.cursor()

sql = "SELECT * FROM customers"
cur.execute(sql)

for (name, address) in cur:
    print(f"{name} {address}")

おまけ(こんな感じで使ったらわかりやすそう)

def find(cursor, table_name, conditions=None):
    # カラム名取得
    cursor.execute(f'DESC {table_name}')
    columns = []
    for c in cursor.fetchall():
        columns.append(c[0])

    sql = f'SELECT * FROM {table_name}'
    if conditions != None:
        where = ' AND '.join(
            map(lambda i: f"`{i[0]}` = '{i[1]}'" if i[1] != None else f"`{i[0]}` IS NULL", conditions.items()))
        sql = f'{sql} WHERE {where}'

    cursor.execute(sql)

    res = []
    for c in cursor:
        # カラム名と取得した値をdictにまとめる
        res.append({k: v for k, v in zip(columns, c)})

    return res

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です