Python连接数据库

来源:互联网 发布:17173英雄联盟数据 编辑:程序博客网 时间:2024/05/22 13:50

下载 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

sudo apt-get install python-dev    (解决fatal error: Python.h: No such file or directory)

CentOS 安装  yum install mysql-devel  和  yum install python-devel(解决error: command 'gcc' failed with exit status 1)


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


3) 验证成功安装

homer@ubuntu:~/myCode/python$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
import MySQLdb
>>> 

import MySQLdb 没有出错,说明安装成功!


测试示例:

[python] view plain copy
  1. import MySQLdb  
  2. db = MySQLdb.connect("localhost","myusername","mypassword","mydb" )  
  3. cursor = db.cursor()  
  4. cursor.execute("SELECT VERSION()")  
  5. data = cursor.fetchone()      
  6. print "Database version : %s " % data      
  7. db.close()  


python 连接mysql示例:

[python] view plain copy
  1. ####################  
  2. # IT-Homer  
  3. # 2013-05-10  
  4. ####################  
  5.   
  6.   
  7. import MySQLdb  
  8.   
  9.   
  10. db = MySQLdb.connect(host="localhost", user="root", passwd="abcd1234", db="testDB")  
  11.   
  12. cursor = db.cursor()  
  13.   
  14. cursor.execute("Select * from gameTestDB limit 10")  
  15. result = cursor.fetchall()  
  16.   
  17. for row in result:  
  18.   #print row  
  19.   #print row[0], row[1], row[2]  
  20.   #print '%s, %s, %s' % (row[0], row[1], row[2])  
  21.   print ', '.join([str(row[0]), str(row[1]), str(row[2])])  
  22.   
  23. cursor.close()  
  24.   
  25.   
  26.   
  27. ''''' 
  28. import sys 
  29. import MySQLdb 
  30.  
  31. reload(sys) 
  32. sys.setdefaultencoding('utf-8') 
  33.  
  34.  
  35. db = MySQLdb.connect(user='root', passwd='abcd1234', charset='utf8') 
  36. cur = db.cursor() 
  37. cur.execute('use testDB') 
  38. cur.execute('select * from gameTestDB limit 10') 
  39.  
  40. f = file("/home/homer/tmp_mysql.txt", 'w') 
  41.  
  42. for row in cur.fetchall(): 
  43.   f.write(str(row)) 
  44.   f.write("\n") 
  45.  
  46. f.close() 
  47. cur.close() 
  48. '''  


[python] view plain copy
  1. ####################  
  2. # IT-Homer  
  3. # 2013-05-10  
  4. ####################  
  5.   
  6.   
  7. import MySQLdb  
  8.   
  9. # local mysql  
  10. # db = MySQLdb.connect(host="localhost", user="root", passwd="abcd1234", db="testDB")  
  11.   
  12. # aws rds mysql  
  13. db = MySQLdb.connect(host="ithomer.aliyun.com", user="ithomer", passwd="abcd1234", db="dman")  
  14.   
  15. cursor = db.cursor()  
  16.   
  17. cursor.execute("Select * from score limit 10")  
  18. result = cursor.fetchall()  
  19.   
  20. for row in result:  
  21.   #print row  
  22.   #print row[0], row[1], row[2]  
  23.   #print '%s, %s, %s' % (row[0], row[1], row[2])  
  24.   print ', '.join([str(row[0]), str(row[1]), str(row[2])])  
  25.   
  26. cursor.close()  
  27.   
  28.   
  29.   
  30. '''  
  31. import sys  
  32. import MySQLdb  
  33.   
  34. reload(sys)  
  35. sys.setdefaultencoding('utf-8')  
  36.   
  37.   
  38. db = MySQLdb.connect(user='root', passwd='abcd1234', charset='utf8')  
  39. cur = db.cursor()  
  40. cur.execute('use testDB')  
  41. cur.execute('select * from gameTestDB limit 10')  
  42.   
  43. f = file("/home/homer/tmp_mysql.txt"'w')  
  44.   
  45. for row in cur.fetchall():  
  46.   f.write(str(row))  
  47.   f.write("\n")  
  48.   
  49. f.close()  
  50. cur.close()  


python 连接mongodb

1) 安装pymongo

pymongo 下载,最新 pymongo-2.6.tar.gz

安装

$ tar zxvf pymongo-2.6.tar.gz
$ cdpymongo-2.6
$ sudo python setup.py build
$ sudo python setup.py install


2)连接mongodb

[python] view plain copy
  1. #!/usr/bin/python  
  2.   
  3. import pymongo  
  4. import random  
  5.   
  6. HOST = '172.27.22.21'  
  7. PORT = 27017  
  8.   
  9. _DB='test'  
  10. _TABLE='testuser'  
  11.   
  12.   
  13. conn = pymongo.Connection("172.27.22.21"27017)  
  14. db = conn[_DB]  # get db  
  15. db.authenticate("yanggang""123456")  
  16.   
  17. table = db[_TABLE]      # get collection  
  18. table.drop()  
  19. table.save({"id":1"name":"homer""age":18})  
  20.   
  21. for id in range(2,10):  
  22.   name = random.choice(['it''homer''sunboy''yanggang'])  
  23.   age = random.choice([102030405060])  
  24.   
  25.   table.insert({"id":id, "name":name, "age":age})  
  26.   
  27. cursor = table.find()  
  28. for user in cursor:  
  29.   print user  
  30.   
  31.   
  32.   
  33. ''''' 
  34. conn = pymongo.Connection("172.27.22.21", 27017) 
  35. db = conn.test 
  36. db.authenticate("yanggang", "123456") 
  37.  
  38. db.testuser.drop() 
  39. db.testuser.save({"id":1, "name":"homer", "age":18}) 
  40.  
  41. for id in range(2,10): 
  42.   name = random.choice(['it', 'homer', 'sunboy', 'yanggang']) 
  43.   age = random.choice([10, 20, 30, 40, 50, 60]) 
  44.  
  45.   db.testuser.insert({"id":id, "name":name, "age":age}) 
  46.  
  47. cursor = db.testuser.find() 
  48. for user in cursor: 
  49.   print user 
  50. '''  

运行结果




python 连接 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

3)验证安装成功:

# python
>>> import redis
>>> 


redis 设置密码

a) 修改配置文件

viim  redis.conf

b) 添加一行

requirepass '123456'

c)重启redis服务

/usr/local/bin/redis-server  /etc/redis.conf

d)登陆 redis-cli

$ redis-cli 
127.0.0.1:6379>
set foo bar
(error) NOAUTH Authentication required.        // 设置了密码,操作没有权限
127.0.0.1:6379> help auth                              // 查看auth命令帮助
  AUTH password
  summary: Authenticate to the server
  since: 1.0.0
  group: connection


127.0.0.1:6379> auth '123456'                       // 输入密码,权限认证

OK
127.0.0.1:6379> set foo bar                           // 密码权限认证成功后,可以操作
OK
127.0.0.1:6379> get foo
"bar"


redis-cli 远程连接

$ redis-cli --help
redis-cli 2.8.12
Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]
  -h <hostname>      Server hostname (default: 127.0.0.1).
  -p <port>          Server port (default: 6379).
  -s <socket>        Server socket (overrides hostname and port).
  -a <password>      Password to use when connecting to the server.


redis-cli 远程连接命令

redis-cli -h 123.10.78.100 -p 6379 -a '123456'

注意:为了安全,redis不要用默认端口(6379),强烈推荐使用密码(requirepass 'xxx'),否则很容易被别人访问!



4)简单示例:

[python] view plain copy
  1. >>> import redis  
  2. >>> r = redis.StrictRedis(host='localhost', port=6379, db=0)  
  3. >>> r.set('foo''bar')  
  4. True  
  5. >>> r.get('foo')  
  6. 'bar'  

5)python脚本示例
[python] view plain copy
  1. #!/usr/bin/python  
  2. # -*- coding: utf-8 -*-  
  3.   
  4. import sys  
  5. reload(sys)  
  6. sys.setdefaultencoding('utf-8')  
  7.   
  8. import redis  
  9.   
  10. _REDIS_HOST = '172.27.9.104'  
  11. _REDIS_PORT = 6379  
  12. _REDIS_DB = 0  
  13.   
  14.   
  15. def read_redis():  
  16.     r = redis.Redis(host=_REDIS_HOST, port=_REDIS_PORT, db=_REDIS_DB)  
  17.   
  18.     # 删除当前数据库的所有数据  
  19.     r.flushdb()               
  20.   
  21.     r.set('foo''bar')  
  22.     print(r.get('foo'))         # bar  
  23.   
  24.     r.set('blog''ithomer.net')  
  25.     r.set('name''yanggang')  
  26.   
  27.     # 查询没有key,返回 None  
  28.     print(r.get('none123'))     # None  
  29.   
  30.     # 库里有多少key,就多少条数据  
  31.     print(r.dbsize())           # 3  
  32.   
  33.     # 列出所有键值  
  34.     print(r.keys())             # ['blog', 'foo', 'name']  
  35.   
  36. if __name__ == "__main__":  
  37.     read_redis()  
运行结果:bar
None
3
['blog', 'foo', 'name']