前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 学习入门(4)—— 连接MySQL

Python 学习入门(4)—— 连接MySQL

作者头像
阳光岛主
发布2019-02-19 10:26:58
5130
发布2019-02-19 10:26:58
举报
文章被收录于专栏:米扑专栏米扑专栏

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

测试示例:

代码语言:javascript
复制
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()

python 连接mysql示例:

代码语言:javascript
复制
####################
# 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()
'''
代码语言:javascript
复制
####################
# 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()

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

代码语言:javascript
复制
#!/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
'''

运行结果

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)简单示例:

代码语言:javascript
复制
>>> import redis
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
'bar'

5)python脚本示例

代码语言:javascript
复制
#!/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()

运行结果:

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)

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2013年10月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档