Pyhton定时生成模拟数据并存入Mysql

来源:互联网 发布:电动汽车推荐 知乎 编辑:程序博客网 时间:2024/06/05 04:44

设计思路:
1.python 使用随机数模块,生成所需要的模拟数据。
2.将模拟数据定时存入mysql
3.设置定时器,定时执行
ps:数据库和表的创建在mysql的shell中以完成,模拟数据存入test表中,每次生成单条记录。

 # -*- coding:utf-8 -*- import MySQLdbimport scheduleimport timeimport datetimeimport randomimport stringclass 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)
0 0