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

使用するために MySQL との接続 Python、あなたはある程度の知識を持っている必要があります SQL

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

何ですか MySQL?

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

インストールする方法 MySQL ボンジョイント Python on 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

インストールを開始する MySQL in Windows

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

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

接続方法はこちら MySQL   Python:

Python 2.7 以下は pip を使用して次のようにインストールします:

pip install mysql-connector

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

pip3 install mysql-connector

テストする MySQL データベース接続 Python

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

アクセスするための構文 MySQL   Python:

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>

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

データベースの作成 MySQL Python

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)

出力:

データベースの作成 MySQL

ここで上の画像は、 my_first_db データベースが作成されました

テーブルを作成する MySQL   Python

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

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',)

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

を作成しましょう Employee XNUMX つの異なる列を持つテーブル。 主キーを追加します id AUTO_INCREMENT制約を持つ列は以下に示すように Python データベース接続を備えたプロジェクト。

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',)

ALTER テーブル MySQL   Python

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 列が変更されます。

ALTER テーブル MySQL

インセット Operaとの関係 MySQL in Python:

挿入操作を実行してみましょう 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 初心者向けチュートリアル: プログラミングの基礎を学ぶ [PDF]