Home > Database > Mysql Tutorial > Python 学习入门(4) 连接MySQL

Python 学习入门(4) 连接MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 15:40:59
Original
1377 people have browsed it

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

下载 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 没有出错,说明安装成功!


测试示例:

import MySQLdb
db = MySQLdb.connect("localhost","myusername","mypassword","mydb" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()    
print "Database version : %s " % data    
db.close()
Copy after login


python 连接mysql示例:

####################
# IT-Homer
# 2013-05-10
####################


import MySQLdb


db = MySQLdb.connect(host="localhost", user="root", passwd="abcd1234", db="testDB")

cursor = db.cursor()

cursor.execute("Select * from gameTestDB limit 10")
result = cursor.fetchall()

for row in result:
  #print row
  #print row[0], row[1], row[2]
  #print '%s, %s, %s' % (row[0], row[1], row[2])
  print ', '.join([str(row[0]), str(row[1]), str(row[2])])

cursor.close()



'''
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()
'''
Copy after login


####################
# IT-Homer
# 2013-05-10
####################


import MySQLdb

# local mysql
# db = MySQLdb.connect(host="localhost", user="root", passwd="abcd1234", db="testDB")

# aws rds mysql
db = MySQLdb.connect(host="ithomer.aliyun.com", user="ithomer", passwd="abcd1234", db="dman")

cursor = db.cursor()

cursor.execute("Select * from score limit 10")
result = cursor.fetchall()

for row in result:
  #print row
  #print row[0], row[1], row[2]
  #print '%s, %s, %s' % (row[0], row[1], row[2])
  print ', '.join([str(row[0]), str(row[1]), str(row[2])])

cursor.close()



'''
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()
Copy after login


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

#!/usr/bin/python

import pymongo
import random

HOST = '172.27.22.21'
PORT = 27017

_DB='test'
_TABLE='testuser'


conn = pymongo.Connection("172.27.22.21", 27017)
db = conn[_DB]  # get db
db.authenticate("yanggang", "123456")

table = db[_TABLE]      # get collection
table.drop()
table.save({"id":1, "name":"homer", "age":18})

for id in range(2,10):
  name = random.choice(['it', 'homer', 'sunboy', 'yanggang'])
  age = random.choice([10, 20, 30, 40, 50, 60])

  table.insert({"id":id, "name":name, "age":age})

cursor = table.find()
for user in cursor:
  print user



'''
conn = pymongo.Connection("172.27.22.21", 27017)
db = conn.test
db.authenticate("yanggang", "123456")

db.testuser.drop()
db.testuser.save({"id":1, "name":"homer", "age":18})

for id in range(2,10):
  name = random.choice(['it', 'homer', 'sunboy', 'yanggang'])
  age = random.choice([10, 20, 30, 40, 50, 60])

  db.testuser.insert({"id":id, "name":name, "age":age})

cursor = db.testuser.find()
for user in cursor:
  print user
'''
Copy after login

运行结果

Python 学习入门(4) 连接MySQL



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

4)简单示例:

>>> import redis
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
'bar'
Copy after login

5)python脚本示例
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import redis

_REDIS_HOST = '172.27.9.104'
_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', 'ithomer.net')
    r.set('name', 'yanggang')

    # 查询没有key,返回 None
    print(r.get('none123'))     # None

    # 库里有多少key,就多少条数据
    print(r.dbsize())           # 3

    # 列出所有键值
    print(r.keys())             # ['blog', 'foo', 'name']

if __name__ == "__main__":
    read_redis()
Copy after login
运行结果:

bar
None
3
['blog', 'foo', 'name']



参考推荐:

Python 連接 MySQL

MySQLdb User's Guide

Python 字符串操作

mysql_config not found(stackover flow)


python 创建mysql数据库

python连接mongodb并操作 

redis-py(github)


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template