http://blog.csdn.net/ithomer/article/details/8911468
mysql
mysql安装
下载 MySQL for Python,最新版 MySQL-python-1.2.4b4.tar.gz
1) 提前安装:mysql_config 环境
否则后面 python setup.py build 会提示找不到 “EnvironmentError: mysql_config not found”,安装命令如下:
sudo apt-get install libmysqlclient-dev
2) 然后,再安装MySQLdb
$ tar zxvf MySQL-python-1.2.2.tar.gz$ cd MySQL-python-1.2.2
$ sudo python setup.py build
$ sudo python setup.py install
mysql使用
import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')
db = MySQLdb.connect(user='root', passwd='abcd1234', charset='utf8')
cur = db.cursor()
cur.execute('use testDB')
cur.execute('select * from gameTestDB limit 10')
f = file("/home/homer/tmp_mysql.txt", 'w')
for row in cur.fetchall():
f.write(str(row))
f.write("\n")
f.close()
cur.close()
redis
redis安装
1)前往 redis-py 下载发布版本 release,最新发布版本: redis-py-2.8.0.zip
2)解压 redis-py-2.8.0.zip: unzip redis-py-2.8.0.zip, 安装: sudo python setup.py install
redis使用
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import redis
_REDIS_HOST = '127.0.0.1'
_REDIS_PORT = 6379;
_REDIS_DB = 0
def read_redis():
r = redis.Redis(host=_REDIS_HOST, port=_REDIS_PORT, db=_REDIS_DB)
# 删除当前数据库的所有数据
r.flushdb()
r.set('foo', 'bar')
print(r.get('foo'))
# bar
r.set('blog', 'csdn.net')
r.set('name', 'heihei')
# 查询没有key,返回 None
print(r.get('none123'))
# None
# 库里有多少key,就多少条数据
print(r.dbsize())
# 3
# 列出所有键值
print(r.keys())
# ['blog', 'foo', 'name']
if __name__ == "__main__":
read_redis()