Python连接数据库

超、凢脫俗 2022-06-05 10:20 302阅读 0赞

下载 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. import MySQLdb
  6. db = MySQLdb.connect(host=”localhost”, user=”root”, passwd=”abcd1234”, db=”testDB”)
  7. cursor = db.cursor()
  8. cursor.execute(“Select * from gameTestDB limit 10”)
  9. result = cursor.fetchall()
  10. for row in result:
  11. #print row
  12. #print row[0], row[1], row[2]
  13. #print ‘%s, %s, %s’ % (row[0], row[1], row[2])
  14. print ‘, ‘.join([str(row[0]), str(row[1]), str(row[2])])
  15. cursor.close()
  16. ‘’’’’
  17. import sys
  18. import MySQLdb
  19. reload(sys)
  20. sys.setdefaultencoding(‘utf-8’)
  21. db = MySQLdb.connect(user=’root’, passwd=’abcd1234’, charset=’utf8’)
  22. cur = db.cursor()
  23. cur.execute(‘use testDB’)
  24. cur.execute(‘select * from gameTestDB limit 10’)
  25. f = file(“/home/homer/tmp_mysql.txt”, ‘w’)
  26. for row in cur.fetchall():
  27. f.write(str(row))
  28. f.write(“\n”)
  29. f.close()
  30. cur.close()
  31. ‘’’

[python] view plain copy

  1. ####################
  2. # IT-Homer
  3. # 2013-05-10
  4. ####################
  5. import MySQLdb
  6. # local mysql
  7. # db = MySQLdb.connect(host=”localhost”, user=”root”, passwd=”abcd1234”, db=”testDB”)
  8. # aws rds mysql
  9. db = MySQLdb.connect(host=”ithomer.aliyun.com”, user=”ithomer”, passwd=”abcd1234”, db=”dman”)
  10. cursor = db.cursor()
  11. cursor.execute(“Select * from score limit 10”)
  12. result = cursor.fetchall()
  13. for row in result:
  14. #print row
  15. #print row[0], row[1], row[2]
  16. #print ‘%s, %s, %s’ % (row[0], row[1], row[2])
  17. print ‘, ‘.join([str(row[0]), str(row[1]), str(row[2])])
  18. cursor.close()
  19. ‘’’
  20. import sys
  21. import MySQLdb
  22. reload(sys)
  23. sys.setdefaultencoding(‘utf-8’)
  24. db = MySQLdb.connect(user=’root’, passwd=’abcd1234’, charset=’utf8’)
  25. cur = db.cursor()
  26. cur.execute(‘use testDB’)
  27. cur.execute(‘select * from gameTestDB limit 10’)
  28. f = file(“/home/homer/tmp_mysql.txt”, ‘w’)
  29. for row in cur.fetchall():
  30. f.write(str(row))
  31. f.write(“\n”)
  32. f.close()
  33. cur.close()

python 连接mongodb

1) 安装pymongo

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

安装

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

2)连接mongodb

[python] view plain copy

  1. #!/usr/bin/python
  2. import pymongo
  3. import random
  4. HOST = ‘172.27.22.21’
  5. PORT = 27017
  6. _DB=’test’
  7. _TABLE=’testuser’
  8. conn = pymongo.Connection(“172.27.22.21”, 27017)
  9. db = conn[_DB] # get db
  10. db.authenticate(“yanggang”, “123456”)
  11. table = db[_TABLE] # get collection
  12. table.drop()
  13. table.save({ “id”:1, “name”:”homer”, “age”:18})
  14. for id in range(2,10):
  15. name = random.choice([‘it’, ‘homer’, ‘sunboy’, ‘yanggang’])
  16. age = random.choice([10, 20, 30, 40, 50, 60])
  17. table.insert({ “id”:id, “name”:name, “age”:age})
  18. cursor = table.find()
  19. for user in cursor:
  20. print user
  21. ‘’’’’
  22. conn = pymongo.Connection(“172.27.22.21”, 27017)
  23. db = conn.test
  24. db.authenticate(“yanggang”, “123456”)
  25. db.testuser.drop()
  26. db.testuser.save({“id”:1, “name”:”homer”, “age”:18})
  27. for id in range(2,10):
  28. name = random.choice([‘it’, ‘homer’, ‘sunboy’, ‘yanggang’])
  29. age = random.choice([10, 20, 30, 40, 50, 60])
  30. db.testuser.insert({“id”:id, “name”:name, “age”:age})
  31. cursor = db.testuser.find()
  32. for user in cursor:
  33. print user
  34. ‘’’

运行结果

20131030133000109

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 Server hostname (default: 127.0.0.1).
-p Server port (default: 6379).
-s Server socket (overrides hostname and port).
-a 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. import sys
  4. reload(sys)
  5. sys.setdefaultencoding(‘utf-8’)
  6. import redis
  7. _REDIS_HOST = ‘172.27.9.104’
  8. _REDIS_PORT = 6379
  9. _REDIS_DB = 0
  10. def read_redis():
  11. r = redis.Redis(host=_REDIS_HOST, port=_REDIS_PORT, db=_REDIS_DB)
  12. # 删除当前数据库的所有数据
  13. r.flushdb()
  14. r.set(‘foo’, ‘bar’)
  15. print(r.get(‘foo’)) # bar
  16. r.set(‘blog’, ‘ithomer.net’)
  17. r.set(‘name’, ‘yanggang’)
  18. # 查询没有key,返回 None
  19. print(r.get(‘none123’)) # None
  20. # 库里有多少key,就多少条数据
  21. print(r.dbsize()) # 3
  22. # 列出所有键值
  23. print(r.keys()) # [‘blog’, ‘foo’, ‘name’]
  24. if __name__ == “__main__“:
  25. read_redis()

运行结果: bar
None
3
[‘blog’, ‘foo’, ‘name’]

发表评论

表情:
评论列表 (有 0 条评论,302人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python连接mysql数据库

    坚持每天学一点,每天积累一点点,作为自己每天的业余收获,这个文章是我在吃饭的期间写的,利用自己零散的时间学了一下python操作MYSQL,所以整理一下。 我采用的是MySQ