为了在外汇交易中获胜,第二部分:MySQL连接
这是前一篇《如何在外汇交易中取胜(第一部分)》的续篇。
我找到了汇率信息,想要将其存入数据库。
我几乎照搬了以下页面作为参考,对此表示很抱歉。
【参考】安装Mariadb到树莓派的笔记
Python3连接MySQL有很多方法,但首先尝试使用PyMySQL。
安装软件包
安装必要的软件包来构建MySQL环境。
pi@raspberrypi:~ $ sudo apt-get update
pi@raspberrypi:~ $ sudo apt-get install mysql-server
pi@raspberrypi:~ $ pip3 install PyMySQL
最后,我不太确定是安装了MySQL还是最终被迫使用了MariaDB,但通过这样做,我被自己说服了这样就完成了MySQL的运行环境。
设置根密码
順便提一句,在樹莓派上从来没有注意过root密码的事情。
为了创建数据库,我会快速进行设置。
pi@raspberrypi:~ $ sudo -i
root@raspberrypi:~# sudo /usr/bin/mysql_secure_installation
# rootに対してパスワードを設定していない場合はEnterで進む
Enter current password for root (enter for none):
# rootに対して新しいパスワードを設定する
Set root password? [Y/n] y
New password: (root のパスワードを設定)
Re-enter new password: (root のパスワードを設定)
Remove anonymous users? [Y/n] y
Disallow root login remotely? [Y/n] y
Remove test database and access to it? [Y/n] y
Reload privilege tables now? [Y/n] y
创建数据库和用户
听说这是要使用root帐户创建的,需要输入root密码。
root@raspberrypi:~# mysql
MariaDB [(none)]> USE mysql;
MariaDB [mysql]> SELECT user,password,plugin FROM user;
+------+-------------------------------------------+-------------+
| user | password | plugin |
+------+-------------------------------------------+-------------+
| root | ***************************************** | unix_socket |
+------+-------------------------------------------+-------------+
1 row in set (0.00 sec)
# unix_socket プラグインは外す
MariaDB [mysql]> UPDATE USER SET plugin='' WHERE user='root';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
MariaDB [mysql]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
MariaDB [mysql]> QUIT;
root@raspberrypi:~# exit
pi@raspberrypi:~ $ mysql -u root -p
Enter password: (root のパスワードを入力)
MariaDB [(none)]> USE mysql;
MariaDB [mysql]> CREATE DATABASE fx;
Query OK, 1 row affected (0.00 sec)
MariaDB [mysql]> CREATE USER 'fxpi'@'localhost' IDENTIFIED BY '(fxpi のパスワードを設定)';
Query OK, 0 rows affected (0.00 sec)
MariaDB [mysql]> GRANT ALL PRIVILEGES ON fx.* TO 'fxpi'@'localhost';
Query OK, 0 rows affected (0.01 sec)
MariaDB [mysql]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
MariaDB [mysql]> SELECT user,password,plugin FROM user;
+------+-------------------------------------------+--------+
| user | password | plugin |
+------+-------------------------------------------+--------+
| root | ***************************************** | |
| fxpi | ***************************************** | |
+------+-------------------------------------------+--------+
2 rows in set (0.00 sec)
MariaDB [mysql]> QUIT;
我会创建数据库“fx”和用户“fxpi”。查询 OK,0 行受影响,但结果已经正确反映了。
创建表格
我們將建立一個記錄匯率的表格。
-
time 日時(日時型)
instrument 通貨ペア(可変長文字列型)
open 始値(不動小数点型)
high 高値(不動小数点型)
low 安値(不動小数点型)
close 終値(不動小数点型)
首先,允许所有列为空。
pi@raspberrypi:~ $ mysql -u fxpi -p
Enter password: (fxpi のパスワードを入力)
MariaDB [(none)]> USE fx;
MariaDB [fx]> CREATE TABLE tbl_candle (time DATETIME, instrument VARCHAR(7), open FLOAT, high FLOAT, low FLOAT, close FLOAT);
Query OK, 0 rows affected (0.07 sec)
MariaDB [fx]> DESCRIBE tbl_candle;
+------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------+------+-----+---------+-------+
| time | datetime | YES | | NULL | |
| instrument | varchar(7) | YES | | NULL | |
| open | float | YES | | NULL | |
| high | float | YES | | NULL | |
| low | float | YES | | NULL | |
| close | float | YES | | NULL | |
+------------+------------+------+-----+---------+-------+
6 rows in set (0.01 sec)
Python 代码
只提供差异部分。
请参考我们公开的 GitHub 获取完整的代码。
import pymysql.cursors
import the module to connect to the database.
# MySQL settings
host="localhost"
user="fxpi"
password="## fxpi's password ##"
db="fx"
charset="utf8mb4"
我将设置所需的连接信息。
# DB connection
conn = pymysql.connect(
host=host,
user=user,
password=password,
db=db,
charset=charset,
cursorclass=pymysql.cursors.DictCursor
)
# Insert DB
try:
for raw in response["candles"]:
with conn.cursor() as cursor:
sql = "INSERT INTO tbl_candle (time, instrument, open, high, low, close) "
sql += "VALUES(%s, %s, %s, %s, %s, %s)"
cursor.execute(sql, (
raw["time"].replace("000Z", "").replace("T", " "),
response["instrument"],
raw[price]["o"],
raw[price]["h"],
raw[price]["l"],
raw[price]["c"]
))
conn.commit()
finally:
conn.close()
实际上会建立连接并执行 INSERT 语句。
即使在执行过程中出现错误,当前的代码将会忽略并继续执行 finally 块。
最后会从数据库断开连接。
每次插入一行数据时都要连接和断开数据库,所以有些低效,但是相比于一个行出现问题导致所有后续行都未处理,我认为这还是好一些。
我已经更改了 `raw[“time”]` 的两个位置,因为 MySQL 发出了一个警告:“日期时间格式我们暂且自行解释好了”,所以这是为了应对这个警告。虽然我不确定这是否正确,但无论如何,警告已经消失了。
输出结果 (Chū lì jié guǒ)
pi@raspberrypi:~ $ mysql -u fxpi -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 284
Server version: 10.1.38-MariaDB-0+deb9u1 Raspbian 9.0
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> USE fx;
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
MariaDB [fx]> SELECT * FROM tbl_candle WHERE instrument="USD_JPY";
+---------------------+------------+---------+---------+---------+---------+
| time | instrument | open | high | low | close |
+---------------------+------------+---------+---------+---------+---------+
| 2019-12-06 14:30:00 | USD_JPY | 108.821 | 108.856 | 108.8 | 108.802 |
| 2019-12-06 14:35:00 | USD_JPY | 108.805 | 108.815 | 108.777 | 108.796 |
| 2019-12-06 14:40:00 | USD_JPY | 108.799 | 108.809 | 108.777 | 108.784 |
+---------------------+------------+---------+---------+---------+---------+
3 rows in set (0.01 sec)
pi@raspberrypi:~ $ mysql -u fxpi -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 284
Server version: 10.1.38-MariaDB-0+deb9u1 Raspbian 9.0
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> USE fx;
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
MariaDB [fx]> SELECT * FROM tbl_candle WHERE instrument="USD_JPY";
+---------------------+------------+---------+---------+---------+---------+
| time | instrument | open | high | low | close |
+---------------------+------------+---------+---------+---------+---------+
| 2019-12-06 14:30:00 | USD_JPY | 108.821 | 108.856 | 108.8 | 108.802 |
| 2019-12-06 14:35:00 | USD_JPY | 108.805 | 108.815 | 108.777 | 108.796 |
| 2019-12-06 14:40:00 | USD_JPY | 108.799 | 108.809 | 108.777 | 108.784 |
+---------------------+------------+---------+---------+---------+---------+
3 rows in set (0.01 sec)
无需操心,蜡烛形态信息已成功写入数据库。
看来只能创建一个网站来展示蜡烛形态了。
继续下去。