PythonでMySQLを利用する方法

pip install mysql-connector-python
project % pip install mysql-connector-python
Collecting mysql-connector-python
  Downloading mysql_connector_python-9.0.0-cp311-cp311-macosx_13_0_arm64.whl.metadata (2.0 kB)
Downloading mysql_connector_python-9.0.0-cp311-cp311-macosx_13_0_arm64.whl (13.4 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 13.4/13.4 MB 25.5 MB/s eta 0:00:00
Installing collected packages: mysql-connector-python
Successfully installed mysql-connector-python-9.0.0

https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html

import mysql.connector

ctx = mysql.connector.connect(
    user="user_name",
    password="password",
    host="localhost",
    port=xxxx,
    database="database_name"
)

cursor = ctx.cursor()

query = ("INSERT INTO table_name (column) VALUES (value)")

cursor.execute(query)

ctx.commit()

cursor.close()
ctx.close()
import mysql.connector

ctx = mysql.connector.connect(
    user="user_name",
    password="password",
    host="localhost",
    port=xxxx,
    database="database_name"
)

cursor = ctx.cursor()

query = ("INSERT INTO table_name (column1, column2) VALUES (%s, %s)")

val = ('xxx', 'xxx')

cursor.execute(query, val)

ctx.commit()

cursor.close()
ctx.close()
import mysql.connector

ctx = mysql.connector.connect(
    user="user_name",
    password="password",
    host="localhost",
    port=xxxx,
    database="database_name"
)

cursor = ctx.cursor()

query = ("INSERT INTO table_name (column1, column2) VALUES (%s, %s)")

val = [
    ('xxx', 'xxx'),
    ('xxx', 'xxx')
]

cursor.executemany(query, val)

ctx.commit()

cursor.close()
ctx.close()

https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html

目次