LoginSignup
4
9

More than 1 year has passed since last update.

PythonでMariaDBに接続

Posted at
1 / 10

概要

AWS Cloud9にて、Pythonでデータ収集し、MariaDBにデータ保存しておくためのスクリプトを作成しました。


依存関係

環境の条件となります。

  • Python – one of the following:
    • CPython >= 3.6
    • Latest PyPy 3
  • MySQL Server – one of the following:
    • MySQL >= 5.6
    • MariaDB >= 10.0

モジュールをインストール

$ pip install PyMySQL
Defaulting to user installation because normal site-packages is not writeable
Collecting PyMySQL
  Downloading PyMySQL-1.0.2-py3-none-any.whl (43 kB)
     |████████████████████████████████| 43 kB 3.8 MB/s 
Installing collected packages: PyMySQL
Successfully installed PyMySQL-1.0.2

事前準備

サンプル用に環境を整えます。

データベースの作成

sampleというデータベースを作成します。

MariaDB [(none)]> CREATE DATABASE sample;
Query OK, 1 row affected (0.00 sec)

ユーザの作成

MariaDB [(none)]> create user 'user'@'localhost' identified by 'passwd';
Query OK, 0 rows affected (0.00 sec)

ユーザへの権限付与

データベース内の全テーブルに与える権限を与える

MariaDB [mysql]> grant all on sample.* to 'user'@'localhost';
Query OK, 0 rows affected (0.00 sec)

MariaDB [mysql]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

テーブルの作成

usersというテーブルを作成します。

CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `email` varchar(255) COLLATE utf8_bin NOT NULL,
    `password` varchar(255) COLLATE utf8_bin NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin
AUTO_INCREMENT=1 ;

これで準備完了です。


pythonファイル

やっていることは、usersテーブルにデータを追加し、追加されているかSELECTで確認をします。

sample.py
import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             database='sample',
                             cursorclass=pymysql.cursors.DictCursor)

with connection:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)

実行し、検索結果を確認

$ python sample.py
{'id': 1, 'password': 'very-secret'}
MariaDB [sample]> select * from users;
+----+----------------------+-------------+
| id | email                | password    |
+----+----------------------+-------------+
|  1 | webmaster@python.org | very-secret |
+----+----------------------+-------------+
1 row in set (0.00 sec)

まとめ

環境さえ整えることが出来れば、DB接続やSQL操作は簡単に行えそうです。
開発がより、はかどりそうです。

参考サイト

4
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
9