Python with MySQL Connectivity:コネクタ、データベースの作成、テーブル、挿入 [例]
Python で MySQL 接続を使用するには、SQL に関する知識が必要です
深く掘り下げる前に、理解しましょう
MySQL とは?
MySQL はオープン ソース データベースであり、RDBMS (リレーショナル データベース管理システム) の中でも最も優れたタイプの 1 つです。 MySQLdb の共同創設者は Michael Widenius であり、MySQL の名前も Michael の娘に由来しています。
このチュートリアルでは、次のことを学びます
- MySQL とは
- MySQL のインストール方法
- Python 用の MySQL コネクタ ライブラリをインストールします
- Python で MySQL データベース接続をテストする
- Python を使用して MySQL にデータベースを作成する
- Python を使用して MySQL にテーブルを作成する
- 主キーを持つテーブルを作成する
- Python を使用した MySQL の ALTER テーブル
- Python で MySQL を使用した挿入操作
MySQL Connector Python を Windows、Linux/Unix にインストールする方法
MySQL を Linux/Unix にインストールする:
公式サイトから 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 を接続する方法は次のとおりです:
pip as を使用して Python 2.7 以前をインストールする場合:
pip install mysql-connector
Python 3 以降のバージョンの場合、pip3 を次のように使用してインストールします。
pip3 install mysql-connector
Python で MySQL データベース接続をテストする
ここで Python で MySQL データベース接続をテストするには、プリインストールされた MySQL コネクタを使用し、認証情報を connect() に渡します。 以下の Python MySQL コネクタの例に示すように、ホスト、ユーザー名、およびパスワードのように機能します。
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 つの異なる列を持つテーブル。 id に主キーを追加します 以下のデータベース接続を備えた Python プロジェクトに示すように、AUTO_INCREMENT 制約のある列
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 でテーブル構造を変更するために使用されます。ここで Student を変更します id に主キーを追加します 以下の Python MySQL コネクタ プロジェクトに示されているフィールド。
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データベーステーブルに挿入操作を行ってみましょう。 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