Python-data-access-python-mysql-database-connection

提供:Dev Guides
移動先:案内検索

Python MySQL-データベース接続

MySQLに接続するには、(1つの方法は)以下に示すようにシステムでMySQLコマンドプロンプトを開きます-

MySQLコマンドプロンプト

ここでパスワードを要求します。インストール時にデフォルトユーザー(root)に設定したパスワードを入力する必要があります。

次に、MySQLとの接続が確立され、次のメッセージが表示されます-

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.12-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>プロンプトでexitコマンドを使用すると、いつでもMySQLデータベースから切断できます。

mysql> exit
Bye

Pythonを使用してMySQLとの接続を確立する

Pythonを使用してMySQLデータベースへの接続を確立する前に、次のことを想定します-

  • mydbという名前のデータベースを作成したこと。

  • FIRST_NAME、LAST_NAME、AGE、SEX、およびINCOME列を含むテーブルEMPLOYEEを作成しました。

  • MySQLとの接続に使用している資格情報は、ユーザー名: root 、パスワード: password です。

    *_connect()_* コンストラクターを使用して接続を確立できます。 これは、ユーザー名、パスワード、ホスト、および接続する必要があるデータベースの名前を受け入れ(オプション)、MySQLConnectionクラスのオブジェクトを返します。

以下は、MySQLデータベース「mydb」と接続する例です。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(user='root', password='password', host='127.0.0.1', database='mydb')

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("SELECT DATABASE()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)

#Closing the connection
conn.close()

出力

実行すると、このスクリプトは次の出力を生成します-

D:\Python_MySQL>python EstablishCon.py
Connection established to: ('mydb',)

以下に示すように、資格情報(ユーザー名、パスワード、ホスト名、データベース名)を connection.MySQLConnection() に渡すことで、MySQLへの接続を確立することもできます-

from mysql.connector import (connection)

#establishing the connection
conn = connection.MySQLConnection(user='root', password='password', host='127.0.0.1', database='mydb')

#Closing the connection
conn.close()