Python3でMySQL・MariaDBへの接続とSQL実行

Pythonで「MySQL」「MariaDB」へ接続する方法を紹介します。

今回はPythonの「mysql.connector」ライブラリを使用して「MySQL」、「MariaDB」に接続します。

※ 「MariaDB」は「MySQL」からフォークしたデータベースです。

PythonとMariaDBを組み合わせる場合は「Python MySQL」で情報を検索すれば大よそ解決することができます。

目次

CGI実行環境

今回使用する実行環境は下になります。

  • CentOS 7(KAGOYA VPS)
  • MariaDB:Version 5.5.56
  • Python:Version 3.6.5

MariaDBのデータベース

今回使用するデータベースの情報は以下になります。

[user@hostname ~]# mysql -u user -p
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

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

MariaDB [(none)]> connect testdb001;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Connection id: 40
Current database: testdb001

MariaDB [testdb001]> select * from tab001;
+------------+------------+
| col01 | col02 |
+------------+------------+
| 0000000001 | 0000000001 |
+------------+------------+
1 row in set (0.00 sec)

Pythonのコード

PythonでMariaDBに接続するためには「mysql.connector」ライブラリを使用します。

import mysql.connector

if __name__ == '__main__':
    connect = mysql.connector.connect(user='<接続ユーザー>',
    password='<パスワード>',
    host='<ホスト名>',
    database='<データベース名>')
    cursor = connect.cursor()

    cursor.execute('select col01, col02 from tab001;')
    for row in cursor.fetchall():
    print(row[0], row[1])

    cursor.close()
    connect.close()

1行目の「mysql.connector.connect()」関数で

  • 接続ユーザー
  • パスワード
  • ホスト名
  • データベース名

を指定します。 8行目でDBに接続しcursorをオープンさせます。 14行目、15行目でカーソルDB接続を終了させます。実行結果は以下になります。

[user@hostname ~]$ python connectMariaDB.py
0000000001 0000000001

退屈なことはPythonにやらせよう ―ノンプログラマーにもできる自動化処理プログラミングposted with ヨメレバ

Al Sweigart オライリージャパン 2017-06-03

Amazon

Kindle

楽天ブックス

7net

honto

e-hon

紀伊國屋書店

よかったらシェアしてね!
  • URLをコピーしました!
目次