ウェブサイト検索

MySQL 接続を備えた Python: データベースとテーブル [例]


Python と MySQL 接続を使用するには、SQL の知識が必要です。

深く掘り下げる前に、理解しましょう

MySQLとは何ですか?

MySQL はオープンソース データベースであり、RDBMS (リレーショナル データベース管理システム) の中で最も優れたタイプの 1 つです。 MySQLdb の共同創設者は Michael Widenius であり、MySQL の名前も Michael Widenius の娘に由来しています。

Windows、Linux/Unix に MySQL コネクタ Python をインストールする方法

Linux/Unix に MySQL をインストールします。

公式サイトから Linux/Unix 用 RPM パッケージをダウンロード: https://www.mysql.com/downloads/

ターミナルで次のコマンドを使用します

rpm  -i <Package_name>
Example   rpm -i MySQL-5.0.9.0.i386.rpm

Linux にチェックインするには

mysql --version

Windows に MySQL をインストールする

公式サイトから MySQL データベース exe をダウンロードし、Windows の通常のソフトウェアのインストールと同様にインストールします。ステップバイステップのガイドについては、このチュートリアルを参照してください

Python 用 MySQL コネクタ ライブラリをインストールする方法

MySQL と Python を接続する方法は次のとおりです。

Python 2.7 以前の場合は、次のように pip を使用してインストールします。

pip install mysql-connector

Python 3 以降のバージョンの場合は、次のように pip3 を使用してインストールします。

pip3 install mysql-connector

Python を使用して MySQL データベース接続をテストする

ここで Python で MySQL データベース接続をテストするには、以下の Python MySQL コネクタの例に示すように、プリインストールされた MySQL コネクタを使用し、ホスト、ユーザー名、パスワードなどの資格情報をconnect() 関数に渡します。

Python を使用して MySQL にアクセスするための構文:

import mysql.connector
	db_connection = mysql.connector.connect(
  	host="hostname",
  	user="username",
  	passwd="password"
    )

:

import mysql.connector
db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root"
)
print(db_connection)

出力:

<mysql.connector.connection.MySQLConnection object at 0x000002338A4C6B00>

ここでの出力は、接続が正常に作成されたことを示しています。

Python を使用して MySQL にデータベースを作成する

SQLで新しいデータベースを作成する構文は次のとおりです。

CREATE DATABASE "database_name"

次に、Python でデータベース プログラミングを使用してデータベースを作成します。

import mysql.connector
  db_connection = mysql.connector.connect(
  host= "localhost",
  user= "root",
  passwd= "root"
  )
# creating database_cursor to perform SQL operation
db_cursor = db_connection.cursor()
# executing cursor with execute method and pass SQL query
db_cursor.execute("CREATE DATABASE my_first_db")
# get list of all databases
db_cursor.execute("SHOW DATABASES")
#print all databases
for db in db_cursor:
	print(db)

出力:

上の画像は、my_first_db データベースが作成されたことを示しています

Python を使用して MySQL にテーブルを作成する

以下の MySQL コネクタの Python の例に示すように、2 つの列を持つ単純なテーブル「student」を作成してみましょう。

SQL 構文:

CREATE  TABLE student (id INT, name VARCHAR(255))

例:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here creating database table as student'
db_cursor.execute("CREATE TABLE student (id INT, name VARCHAR(255))")
#Get database table'
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
	print(table)

出力:

 ('student',)

主キーを使用してテーブルを作成する

3 つの異なる列を持つ従業員テーブルを作成しましょう。以下のデータベース接続のある Python プロジェクトに示すように、AUTO_INCREMENT 制約を使用して id 列に主キーを追加します。

SQL 構文:

CREATE TABLE employee(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), salary INT(6))

:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here creating database table as employee with primary key
db_cursor.execute("CREATE TABLE employee(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), salary INT(6))")
#Get database table
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
	print(table)

出力:

('employee',) ('student',)

Python を使用した MySQL の ALTER テーブル

AlterコマンドはSQLでテーブル構造を変更するために使用します。ここでは、以下の Python MySQL コネクタ プロジェクトに示すように、Student テーブルを変更し、 主キーを id フィールドに追加します。

SQL 構文:

ALTER TABLE student MODIFY id INT PRIMARY KEY

:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
#Here we modify existing column id
db_cursor.execute("ALTER TABLE student MODIFY id INT PRIMARY KEY")

出力:

以下では、 id 列が変更されていることがわかります。

Python で MySQL を使用した挿入操作:

作成済みの MySQL Database テーブルに挿入操作を実行してみましょう。 STUDENT テーブルと EMPLOYEE テーブルにデータを挿入します。

SQL 構文:

INSERT INTO student (id, name) VALUES (01, "John")
INSERT INTO employee (id, name, salary) VALUES(01, "John", 10000)

:

import mysql.connector
  db_connection = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="root",
  database="my_first_db"
  )
db_cursor = db_connection.cursor()
student_sql_query = "INSERT INTO student(id,name) VALUES(01, 'John')"
employee_sql_query = " INSERT INTO employee (id, name, salary) VALUES (01, 'John', 10000)"
#Execute cursor and pass query as well as student data
db_cursor.execute(student_sql_query)
#Execute cursor and pass query of employee and data of employee
	db_cursor.execute(employee_sql_query)
db_connection.commit()
print(db_cursor.rowcount, "Record Inserted")

出力:

 2 Record Inserted

こちらもチェックしてください: - 初心者向け Python チュートリアル: プログラミングの基礎を学ぶ [PDF]

関連記事