PythonとMySQLを連携させるためには、MySQL Connector/Pythonというライブラリが一般的に使用されます。このライブラリは、PythonからMySQLサーバーと通信するための自己完結型のドライバーであり、Python Database API Specification v2.0 (PEP 249)に準拠したAPIを提供します。
MySQL Connector/Pythonのインストール
MySQL Connector/Pythonのインストールはpipを使用して簡単に行うことができます。
pip3 install mysql-connector-python
データベースへの接続
データベースへの接続は以下のように行います。
import mysql.connector
connection = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='myDB'
)
データベース操作
データベースへのクエリの実行は、作成したconnectionオブジェクトからcursorを作成し、そのcursorを使用してSQL文を実行します。
with connection:
with connection.cursor() as cursor:
# レコードを挿入
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('[email protected]', 'very-secret'))
# コミットしてトランザクション実行
connection.commit()
以上がPythonとMySQL Connectorを使用したデータベース操作の基本的な流れです。これを基に、より複雑なデータベース操作をPythonから行うことが可能となります。.