python + docker, 实现天气数据 从FTP获取以及持久化(二)-- python操作MySQL数据库
前言
在这一节中,我们主要介绍如何使用python操作MySQL数据库。
准备
MySQL数据库使用的是上一节中的docker容器 “test-mysql”.

Python 操作 MySQL
我们使用的IDE是 “神奇” 的 pycharm:
1. 首先新建一个python的项目,并且安装 “mysql-connector-python”。

“mysql-connector-python” 是MySQL官方对于python的数据驱动,感兴趣的童鞋可以移步这里: https://dev.mysql.com/doc/connector-python/en/
2. 创建 MySQLUtil.py
基于上一节的介绍,我们的任务是要读取FTP上的文本文件,从中解析出天气数据,并且插入到数据库表中(持久化)。因此,我们将基本的数据库操作都封装到这个python 文件中。
3. 准备工作 -- 在第一次连接的时候需要DDL操作(创建相应的数据库和表); 之后的的操作是DML(增/删/改/查)
# -*- coding: utf-8 -*- from __future__ import print_function import mysql.connector
from mysql.connector import errorcode config_prepare = {
'user': 'root',
'password': 'password',
'host': '127.0.0.1',
#'database': 'weather_db',
'raise_on_warnings': True,
} config_op = {
'user': 'root',
'password': 'password',
'host': '127.0.0.1',
'database': 'weather_db',
#'raise_on_warnings': True,
} def preparation(db_name='weather_db', table_name='weather'):
try:
cnx = mysql.connector.connect(**config)
except mysql.connector.Error as err:
print(err)
return (-1) # try use db or create it
try:
cursor = cnx.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET 'UTF8MB4'".format(db_name))
cnx.database = db_name
except mysql.connector.Error as err:
print(err)
#return (-2) # Create table if not exist
try:
cnx.database = db_name
cursor = cnx.cursor()
createTableSql = """CREATE TABLE IF NOT EXISTS `weather` ( \
`weather_timestamp` varchar(32) NOT NULL, \
`weather_data` varchar(256) NOT NULL, \
PRIMARY KEY (`weather_timestamp`) \
) ENGINE=InnoDB;""" cursor.execute(createTableSql)
cursor.close()
except mysql.connector.errorcode as err:
print(err.msg)
return (-3) print ("Preparation OK") return (0)
4. 插入或更新数据
def insert_or_update_weather_data(datas):
sql = "INSERT INTO weather(weather_timestamp, weather_data) " \
"VALUES(%s,%s)" \
"ON DUPLICATE KEY UPDATE weather_data = VALUES(weather_data);" try:
cnx = mysql.connector.connect(**config_op) cursor = cnx.cursor()
cursor.executemany(sql, datas) cnx.commit() except mysql.connector.errorcode as e:
print('Error:', e)
return (-1) finally:
cursor.close()
cnx.close() return (0)
PS: 由于天气数据是由供应商提供,提供的方式是 每日两次(早上8点;下午5点)放到FTP上面,每次提供7天的天气预报。 因此,当我们读取天气数据的时候,有一段时间的数据是重合的。因此采用插入或更新 (表中没有天气数据时:插入; 有数据时:更新)的方式来处理。
5. 根据时间条件,读取天气数据
def query_weather_data(begin_time_stamp, end_time_stamp):
sql = "SELECT weather_timestamp, weather_data FROM weather " \
"WHERE weather_timestamp BETWEEN %s AND %s;"
try:
cnx = mysql.connector.connect(**config_op)
cursor = cnx.cursor()
# The second parameter must be a tuple that contains all the delimeters
cursor.execute(sql, (begin_time_stamp, end_time_stamp))
rows = cursor.fetchall()
return rows
except mysql.connector.errorcode as e:
print('Error:', e)
return []
finally:
cursor.close()
cnx.close()
6. 最后附上测试代码
if __name__ == '__main__':
print("=== Unit test begin ===") # Test prepareation
nRet = preparation() # Test insert or update datas in 'weather' table
datas1 = (
('', '0.0 0.0 0.0 16.461 95.163 6.038 97.493 1013.791'),
('', '0.0 0.0 0.0 16.347 95.532 6.046 97.606 1013.713'),
('', '0.0 0.0 0.0 16.233 95.901 6.055 97.719 1013.634'),
('', '0.0 0.0 0.0 16.139 96.269 6.063 97.832 1013.556'),
)
nRet1 = insert_or_update_weather_data(datas1) datas2 = ( ('', '{data1:0.0, data2:0.0, data3:0.0, data4:16.233, data5:95.901, data6:6.055, data7:97.719, data8:1013.030}'),
('', '{data1:0.0, data2:0.0, data3:0.0, data4:11.111, data5:93.901, data6:6.099, data7:97.700, data8:1013.045}'),
)
nRet2 = insert_or_update_weather_data(datas2) # Test query data from 'weather' table
ret_list = query_weather_data('', '')
if len(ret_list) == 0:
print ("No data queried out.")
else:
for timestamp, data in ret_list:
print ('timestamp:%s data:%s' %(timestamp, data)) print("=== Unit test done ===")
小结
至此,我们操作MySQL的工具代码就全部编写完成。 在下一节中,我们将着重FTP部分的说明。
感谢大家的收看,欢迎积极留言讨论~~
python + docker, 实现天气数据 从FTP获取以及持久化(二)-- python操作MySQL数据库的更多相关文章
- python + docker, 实现天气数据 从FTP获取以及持久化(一)
前情提要 最近项目需要天气数据(预报和历史数据)来作为算法程序的输入. 项目的甲方已经购买了天气数据, 依照他们的约定,天气数据的供应商会将数据以"文本" (.TXT)的方式发到F ...
- python + docker, 实现天气数据 从FTP获取以及持久化(五)-- 利用 Docker 容器化 Python 程序
背景 不知不觉中,我们已经完成了所有的编程工作.接下来,我们需要把 Python 程序 做 容器化 (Docker)部署. 思考 考虑到项目的实际情况,“持久化天气”的功能将会是一个独立的功能模块发布 ...
- python + docker, 实现天气数据 从FTP获取以及持久化(四)-- 数据准备
前情提要 在之前的文章里,我们已经掌握从FTP上面下载天气数据然后插入到数据库中. 但是如何将我们已有的数据放到生产环境中呢? 思考 首先,我们先简单的理一理现在的情况. 目前: FTP上面已有半个月 ...
- python + docker, 实现天气数据 从FTP获取以及持久化(三)-- python获取FTP数据
前言 经过前面两个小节的介绍,我们已经完成了MySQL数据库的搭建和数据库操作的事宜. 在本小节中,我们需要完成的任务是:使用python从FTP服务其上面获取文本文件. 搭建测试FTP服务器 LZ的 ...
- 毕设之Python爬取天气数据及可视化分析
写在前面的一些P话:(https://jq.qq.com/?_wv=1027&k=RFkfeU8j) 天气预报我们每天都会关注,我们可以根据未来的天气增减衣物.安排出行,每天的气温.风速风向. ...
- Dapper操作MySQL数据库获取JSON数据中文乱码
前言 在项目中利用Dapper将JSON数据存储到MySQL数据库,结果发现JSON数据中的中文乱码,特此记录,希望对存储JSON的童鞋能有所帮助,文中若有错误之处,还望批评指正. Dapper获取J ...
- python操作mysql数据库的相关操作实例
python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...
- python【第十二篇下】操作MySQL数据库以及ORM之 sqlalchemy
内容一览: 1.Python操作MySQL数据库 2.ORM sqlalchemy学习 1.Python操作MySQL数据库 2. ORM sqlachemy 2.1 ORM简介 对象关系映射(英语: ...
- 使用python操作mysql数据库
这是我之前使用mysql时用到的一些库及开发的工具,这里记录下,也方便我查阅. python版本: 2.7.13 mysql版本: 5.5.36 几个python库 1.mysql-connector ...
随机推荐
- 51Nod 1503 猪和回文
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1503 思路: 没想到要用DP去解决. 题目是从起点出发走,我们可以从起点 ...
- 51Nod 1557 两个集合(二分)
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1557 题意: 小X有n个互不相同的整数: p1,p2,...,pn .他 ...
- Pandas 练习题
1. 使用 pandas 中的函数,下载上证综指过去一段时间的数据,进行数据探索. 上证综指,全称是上海证券综合指数,是以上证所挂牌上市的全部股票为计算范围,以发行量为权数的加权综合股价指数.这一指数 ...
- spring boot: 输出json
spring boot: 输出json 注意:关闭java的Terminate后,在重新启动,否则报错 app.java启动配置 package com.muyang.boot1; import o ...
- Java网络编程和NIO详解6:Linux epoll实现原理详解
Java网络编程和NIO详解6:Linux epoll实现原理详解 本系列文章首发于我的个人博客:https://h2pl.github.io/ 欢迎阅览我的CSDN专栏:Java网络编程和NIO h ...
- Tensorflow学习笔记二
现在来开始安装Tensorflow吧 Tensorflow有两种模式, 一种GPU支持, 另外一种仅CPU支持 虚拟机仅有CPU支持, 那就第一种模式吧 有4种途径去安装 virtualenv &qu ...
- Invalid bound statement (not found)错误的可能原因
其他原因导致此问题解决参考: 1.检查xml文件所在package名称是否和Mapper interface所在的包名 <mapper namespace="me.tspace.pm. ...
- 用于调试的printf函数和自定义log函数
1. 用宏定义调试用的DPRINT #define DEBUG_ENABLE #ifdef DEBUG_ENABLE #define DPRINT(fmt, args...) fprintf(stde ...
- CUDA Samples: matrix multiplication(C = A * B)
以下CUDA sample是分别用C++和CUDA实现的两矩阵相乘运算code即C= A*B,CUDA中包含了两种核函数的实现方法,第一种方法来自于CUDA Samples\v8.0\0_Simple ...
- 简单CSS3代码实现立方体以及3D骰子
1 实现3D立方体 首先准备好UL以及6个Li: 代码如下 ul { position: absolute; top: 50%; left: 50%; transform:translate(-50% ...