小白学Python---用python操作数据库

python操作MySQL

Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口。
不同的数据库你需要下载不同的DB API模块,这里使用的MySQL中的pymysql模块。
DB-API 是一个规范. 它定义了一系列必须的对象和数据库存取方式, 以便为各种各样的底层数据库系统和多种多样的数据库接口程序提供一致的访问接口 。
Python的DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同的方式操作各数据库。
Python DB-API使用流程:

  • 引入 API 模块。
  • 获取与数据库的连接。
  • 执行SQL语句和存储过程。
  • 关闭数据库连接。
# -*- coding:utf-8 -*-
import pymsql

# 1、连接,以下是连接本地的MySQL,如果连接阿里云服务器的database,host的ip要改变
db = pymysql.Connect(
	host='localhost',
	user='root',
	passwd='xxxxxx',
	db='scc',
	port=3306,
	charset='utf8')

# 2、获取游标
cursor = db.cursor()

#3、执行sql语句
try:
        sql = ''' delete from tbstudent where stuid = "1020" '''
        cursor.execute(sql)
        db.commit()
except:
        #事务回滚,即出现错误后,不会继续执行,而是回到程序未执行的状态,原先执行的也不算了
        db.rollback()

db.close()

python操作MySQL,Redis

习题:输入用户名和密码,先去redis查看是否匹配,如果不匹配进入本地MySQL查看是否匹配,如果匹配则刷新redis里面的存储记录。

# -*- coding:utf-8 -*-

import sys
import pymysql
import redis

def con_mysql(sql):
	db = pymysql.connect(
		host = '127.0.0.1',
		user = 'root',
		passwd = 'xxxx',
		port = 3306,
		db = 'scc',
		charset = 'utf8')

	cursor = db.cursor()
	cursor.execute(sql)
	data = cursor.fetchall()
	db.close()

	return data

def con_redis(name, passwd):
	r = redis.Redis(host='x.x.x.x', port=6379, password='12345')
	r_name = r.hget('user','name')
	r_passwd = r.hget('user','passwd')
	# 得到是byte类型,需要解码
	r_name = r_name.decode('utf8')
	r_passwd = r_passwd.decode('utf8')
	if name == r_name and passwd == r_passwd:
		return True, '登陆成功' #返回一个元组
	else:
		return False, '登录失败'


if __name__ == '__main__':
	# 获取传入的姓名和密码参数
	name = sys.argv[1]
	passwd = sys.argv[2]
	# 传入redis中,进行校验
	result = con_redis(name, passwd)
	if not result[0]:
		# 登录失败,查询数据库
		sql = '''select * from stu where name="%s" and passwd="%s" ''' % (name, passwd)
		data = con_mysql(sql)
		if data:
			r = redis.Redis(host='x.x.x.x', port=6379, password='12345')
			r.hset('user', 'name', name)
			r.hset('user', 'passwd', passwd)
			print('刷新redis,登录成功')
		else:
			print('用户名和密码错误')
	else:
		print('redis中数据正确,登录成功')            

Redis 发布订阅

Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)订阅消息,客户端可以订阅任意数量的频道。
下图展示了频道channel1,以及订阅这个频道的三个客户端——client2,client5,client1之间的关系:

当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端:

实例演示:

# 建立channel
# -*- coding:utf-8 -*-

import redis

class RedisBase(object):

	def __init__(self):

		self.__conn = redis.Redis(host='119.23.255.177', port=6379, password='12345')
		self.pub = 'test'
		self.sub = 'test'

	# 发布
	def publish_msg(self,msg):
		# publish 指定channel, message,用于将信息发送到指定的频道。
		self.__conn.publish(self.pub, msg)

	# 订阅
	def subscribe_msg(self):

		pub = self.__conn.pubsub()
		pub.subscribe(self.pub)
		pub.parse_response()
		return pub
# 建立订阅者
# -*- conding:utf-8 -*-

from channel import RedisBase

obj = RedisBase()
redis_sub = obj.subscribe_msg()

while True:
	msg = redis_sub.parse_response()
	print('msg:%s' % msg)
# 建立发布者
# -*- coding:utf-8 -*-

from channel import RedisBase

obj = RedisBase()
msg = 'hello world'
obj.publish_msg(msg)

原文地址:https://www.cnblogs.com/bbszc520/p/8900097.html