|
项目需要python
简单示例
表结构
1 CREATE TABLE `slevin` (
2 `id` int(5) NOT NULL DEFAULT '0',
3 `name` char(10) DEFAULT NULL,
4 PRIMARY KEY (`id`)
5 ) ENGINE=InnoDB DEFAULT CHARSET=latin1 查看表的内容
1 mysql> select * from slevin;
2 +----+------+
3 | id | name |
4 +----+------+
5 | 1 | o |
6 | 2 | h |
7 | 3 | c |
8 | 4 | d |
9 | 5 | e |
10 | 6 | f |
11 | 7 | a |
12 | 8 | b |
13 | 9 | c |
14 | 10 | d |
15 | 11 | e |
16 | 12 | f |
17 +----+------+
18 12 rows in set (0.00 sec) 以下是python操作memcache的脚本
1 import MySQLdb, memcache, hashlib
2 import MySQLdb.cursors
3 #建立一个简单hash算法函数
4 def hash(obj):
5 m=hashlib.md5()
6 m.update(obj)
7 key=m.hexdigest()
8 return key
9 #返回字典式的元组(cursorclass = MySQLdb.cursors.DictCursor)
10 conn = MySQLdb.connect (host = "192.168.1.254",user = "root",passwd = "000000",db = "test",cursorclass = MySQLdb.cursors.DictCursor)
11 mc = memcache.Client(['192.168.1.254:11211'],debug=0)
12 #cursor = conn.cursor ()
13 two=conn.cursor ()
14 two.execute ("select * from slevin")
15 row=two.fetchall()
16 #mc.flush_all()
17 if not mc.get(hash("slevin2")):
18 for i in row:
19 #用HASH(表名+id值)做为KEY,把一行的记录存储到一个key里面
20 tabname='slevin'
21 tabname=tabname+str(i.values()[0])
22 mc.add(hash(tabname),i)
23 #print mc.get(hash(tabname))
24 else:
25 value=mc.get(hash("slevin2"))
26 for key in value.keys():
27 print "%s is %s" %(key,value[key])
28 mc.disconnect_all()
29 cursor.close ()
30 conn.close () |
|
|