Python 练习册--存入数据库(Mongodb,MySQL)操作

来源:互联网 发布:旅游景点地图软件 编辑:程序博客网 时间:2024/06/05 12:42

原理

生成激活码,再存入,主要是数据库的操作,就这么简单。

这里操作MySQL的时候,先写入一条,获得id,然后再更新该条记录。

实现

这里环境的搭建,数据库的安装等略过。

  1. Mongodb

    def save_mongodb():    from pymongo import Connection    conn = Connection('127.0.0.1',27017)    db = conn.codes   #连接codes集合,相当于MySQL中的表    db.codes.drop()    for i in range(10,400,35):        code = activation_code(i)        deadtime = time.time() + timedelta(hours=+12).seconds        db.codes.insert({            "id": i,            "code": code,            "deadtime": deadtime,            }            )    # 插入结果    content = db.codes.find()    for i in content:        print i
  2. MySQL

    def save_mysql():    import MySQLdb    conn=MySQLdb.connect(host='localhost',user='root',passwd='',db='test',port=3306)    cur = conn.cursor()    create_table = '''create table codes(       id                    int not null auto_increment,       codes                 varchar(50) not null,       deadtime              varchar(50) not null,       primary key (id)    );'''    cur.execute('drop table if exists codes;')    cur.execute(create_table)    for i in range(5):        deadtime = time.time() + timedelta(hours=+12).seconds        sql = '''insert into codes(codes, deadtime) values("Newcodes",%s)''' %deadtime        cur.execute(sql)        id = conn.insert_id()        code = activation_code(id)        update_sql = '''update codes set codes = "%s" where id = %s''' %(code, id)        cur.execute(update_sql)    cur.execute("select * from codes;")    content =  cur.fetchall()    for i in content:        print i     cur.close()    conn.commit()    conn.close()

结果

{u'code': u'aL1jcauI6e', u'_id': ObjectId('54ac9d8edc14c634446eff06'), u'id': 10, u'deadtime': 1420641870.316111}{u'code': u'2dLGKFdZFb', u'_id': ObjectId('54ac9d8edc14c634446eff07'), u'id': 45, u'deadtime': 1420641870.328505}{u'code': u'50LBgTXYDG', u'_id': ObjectId('54ac9d8edc14c634446eff08'), u'id': 80, u'deadtime': 1420641870.344679}{u'code': u'73LaYhNYFc', u'_id': ObjectId('54ac9d8edc14c634446eff09'), u'id': 115, u'deadtime': 1420641870.378057}{u'code': u'96LePg91wX', u'_id': ObjectId('54ac9d8edc14c634446eff0a'), u'id': 150, u'deadtime': 1420641870.389882}{u'code': u'b9LrOg4Own', u'_id': ObjectId('54ac9d8edc14c634446eff0b'), u'id': 185, u'deadtime': 1420641870.408178}(1L, '1LLF6MDLXl', '1420648165.64')(2L, '2LLPkDNz3E', '1420648165.64')(3L, '3LLYrtbVW2', '1420648165.64')(4L, '4LLNbrRx75', '1420648165.65')(5L, '5LL0A7vb20', '1420648165.65')

总结

看出来,Mongodb 好用多了,NoSQL比起非关系型数据库看来

  1. 低延迟的读写速度
  2. 支撑海量的数据和流
  3. 大规模集群的管理

更能适应云计算发展。唉,买了本Mongodb权威指南,才看了一点,又闲置了。


参考地址:

  1. python操作mysql数据库
  2. python连接mongodb并操作
  3. MySQLdb User's Guide

0 0