PyMySQL
PythonからMySQLを操作するパッケージ。
PyMySQL/PyMySQL
ubuntu:~$ pip3 install PyMySQL
Requirement already satisfied: PyMySQL in ./.local/lib/python3.8/site-packages (0.10.1)
既存のテーブルにレコードを追加する
データベース test、テーブル table1 に値を追加します。
mysqlユーザやデータベースは作成済みです。(それぞれ、ubuntu, test)
import pymysql.cursors
# MySQLに接続
connection = pymysql.connect(host='localhost',
user='ubuntu',
password='ubuntu',
db='test',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
# レコードを挿入
with connection.cursor() as cursor:
sql = "INSERT INTO table1 VALUE ('2020-09-25 01-14-11','python',888);"
cursor.execute(sql)
# 変更をコミット
connection.commit()
# 切断
connection.close()
既存のテーブル table1 はこんな感じ
mysql> USE test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> desc table1;
+--------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| time | datetime | YES | | NULL | |
| value | char(10) | YES | | NULL | |
| number | int | YES | | NULL | |
+--------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)
python 実行後の table1 を確認
mysql> SELECT * FROM table1;
+---------------------+-----------+--------+
| time | value | number |
+---------------------+-----------+--------+
| 2020-09-25 01:14:11 | python | 888 |
+---------------------+-----------+--------+
1 rows in set (0.00 sec)