Pyhton定时生成模拟数据并存入Mysql
2016-07-22 10:36
531 查看
设计思路:
1.python 使用随机数模块,生成所需要的模拟数据。
2.将模拟数据定时存入mysql
3.设置定时器,定时执行
ps:数据库和表的创建在mysql的shell中以完成,模拟数据存入test表中,每次生成单条记录。
1.python 使用随机数模块,生成所需要的模拟数据。
2.将模拟数据定时存入mysql
3.设置定时器,定时执行
ps:数据库和表的创建在mysql的shell中以完成,模拟数据存入test表中,每次生成单条记录。
# -*- coding:utf-8 -*- import MySQLdb import schedule import time import datetime import random import string class SaveToSql(object): def __init__(self, conn): self.conn = conn # 生成随机数函数 def random_str(self, randomlength=random.randint(1,10)): a = list(string.ascii_letters) random.shuffle(a) return ''.join(a[:randomlength]) # 存储函数 def save(self): cursor = self.conn.cursor() try: sql = "insert into test(time, name, type, data) values('%s','%s', '%s', '%s')"% (datetime.datetime.now(),self.random_str(),self.random_str(),self.random_str()) cursor.execute(sql) print('Insert the data: ', sql) rs = cursor.rowcount """判断数据库表中数据所影响行数是否为1, 如果不是的话就进行异常抛出""" if rs != 1: raise Exception("Error of data inserting.") self.conn.rollback() self.conn.commit() finally: cursor.close() if __name__ == "__main__": conn = MySQLdb.connect( host = '127.0.0.1', port = 3306, user = 'root', passwd = '', db = 'test', charset = 'utf8' ) def job(): save_data = SaveToSql(conn) save_data.save() try: schedule.every(10).seconds.do(job) except Exception as e: print('Error: %s'% e) # finally: # conn.close() while True: schedule.run_pending() time.sleep(1)
相关文章推荐
- MySQL中的integer 数据类型
- MySQL存储过程
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- mysql中int、bigint、smallint 和 tinyint的区别与长度
- mysql load data 导出、导入 csv
- install and upgrade scrapy
- source命令执行SQL脚本文件
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- MySQL创建用户及权限控制
- MySQL管理数据表