最近闲来蛋疼,看见众人都在玩python,于是自己也没事看了看,搞出一个简单的小脚本。俺是python新手,如果有很多地方 不规范或者有错误,请指出!
mysql和memcache的安装我就不说了,网上大把教程
首先看表结构
- CREATE TABLE `slevin` (
- `id` int(5) NOT NULL DEFAULT '0',
- `name` char(10) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1
查看表的内容
- mysql> select * from slevin;
- +----+------+
- | id | name |
- +----+------+
- | 1 | o |
- | 2 | h |
- | 3 | c |
- | 4 | d |
- | 5 | e |
- | 6 | f |
- | 7 | a |
- | 8 | b |
- | 9 | c |
- | 10 | d |
- | 11 | e |
- | 12 | f |
- +----+------+
- 12 rows in set (0.00 sec)
以下是python操作memcache的脚本
- import MySQLdb, memcache, hashlib
- import MySQLdb.cursors
- #建立一个简单hash算法函数
- def hash(obj):
- m=hashlib.md5()
- m.update(obj)
- key=m.hexdigest()
- return key
- #返回字典式的元组(cursorclass = MySQLdb.cursors.DictCursor)
- conn = MySQLdb.connect (host = "192.168.1.254",user = "root",passwd = "000000",db = "test",cursorclass = MySQLdb.cursors.DictCursor)
- mc = memcache.Client(['192.168.1.254:11211'],debug=0)
- #cursor = conn.cursor ()
- two=conn.cursor ()
- two.execute ("select * from slevin")
- row=two.fetchall()
- #mc.flush_all()
- if not mc.get(hash("slevin2")):
- for i in row:
- #用HASH(表名+id值)做为KEY,把一行的记录存储到一个key里面
- tabname='slevin'
- tabname=tabname+str(i.values()[0])
- mc.add(hash(tabname),i)
- #print mc.get(hash(tabname))
- else:
- value=mc.get(hash("slevin2"))
- for key in value.keys():
- print "%s is %s" %(key,value[key])
- mc.disconnect_all()
- cursor.close ()
- conn.close ()