DB-API(redis,mysql)

DB-API

- API理解为应用程序编程接口(函数,方法,URL)
- DB-API就是数据库接口,方便操作数据库,减少编程难度

Redis

1.安装第三方库(python的Redis库):pip install redis
2.连接:conn = redis.Strict Redis(
			host='localhost'	#默认值,可不填,Redis一般不连外网
			port=6379
			db=0	#0-15一共十六个库
			decode_responses=True)	#返回string,默认是False,返回bytes 
3.操作

操作

- 在python中操作Redis的命令和命令行几乎一致,除了del,因为和python中的关键字重名,用delete替代,其他基本一样
1.key操作:res = conn.keys('*')	#查看所有的key,返回一个key列表
		     删除:delete,res = conn.delete('xxx')	#删除key‘xxx’
		     #如果存在,返回1,不存在返回0
		     res = conn.exists('xxx')  # 检查某个key是否存在 不存在返回false
		     print(res)
		     res = conn.rename('set', 'new_set')  # 改名,必须存在,不存在报错
		     res = conn.expire('new_set', 100)  # 设置过期时间,可以是秒数,可以是datetime.timedelta类型,print成功返回True
			conn.ttl('somekey')  # 查看过期时间
			res = conn.persist('new_set')  # 删除过期时间
			print(res)  # 成功返回True
			conn.type('somekey')  # 返回类型
2.string操作:res = conn.get("name")		#查询数据
			res = conn.set("age","18")	#设置,成功返回true
			res = conn.append("age","0")	#追加,返回字符串长度
			print(conn.get("age"))	#返回180
3.hash操作:res = conn.hset("hash","name","xiaoge")	
			#设置一个键值对一次只能加一个,成功返回1
			res = conn.hmset("hash",{"hobby":"girl","height":"174"})
			#设置多个,成功返回true
			res = conn.hgetall("hash")	#查询,输出类型:字典
			conn.hvals('hash')  # 获取所有的值
			conn.hkeys('hash')  # 查看所有键值对的键
4.list操作:     conn.lpush('list', 'value1', 'value2') # 头部添加
			res = conn.lpush("list","xiaoge","na","wenwen","jingyi")
			print(res)		#返回个数
			conn.rpush('somekey', 'value1', 'value2') # 尾部添加
			conn.lrange('somekey', 0, -1)  # 查索引范围内的数据
			conn.lindex('somekey', index)  # 查指定索引数据
			conn.lset('somekey', index, value)  # 修改指定索引数据
			conn.lpop('somekey')  # 删除并返回第一个数据
			conn.rpop('somekey')  # 删除并返回最后一个数据

5.set:		conn.sadd('somekey', 'value1', 'value2')  # 添加数据
			conn.smembers('somekey')  # 查看数据
			conn.spop('somekey')  # 随机删除并返回一个值
			conn.srem('somekey', 'value1', 'value2')  # 指定删除值

6.sorted set
		map = {
		    'xinlan': 100,
		    'tuple': 99,
		    'budong': 98,
		    'feifei': 101,
		}
		res = conn.zadd('somekey', mapping=map)  # 添加数据
		# print(res)
		res = conn.zrange('somekey', 0, -1)  # 查看数据
		conn.zrem('somekey', 'budong', 'tuple')  # 删除数据
		conn.zremrangebyrank('somekey', 0, -1)  # 删除索引范围内的数据
		conn.zremrangebyscore('somekey', 99, 100)  # 删除分数范围内的数据
		conn.zscore('somekey', 'feifei')  # 返回成员分数值

pymysql

安装:

- 第三方库:pymysql,最流行
pip install pymysql

使用步骤:

1.连接:conn = pymysql.connect(user="root",password="qwe123",db="xiaoge",charset="utf8")	#切记不是utf-8
2.创建游标;游标就是运送数据的小车,执行各种命令就靠它
cursor = conn.cursor()
3.执行sql语句
cursor.execute(sql)	#执行sql语句都是通过这个方法
4.获取结果
cursor.fetchall()		#获取所有结果
cursor.fetchone()	#获取一条结果
5.关闭游标
cursor.close()
6.关闭连接
conn.close()

案例

1.pymysql的基本使用步骤
#pymysql的简单使用with语句
import pymysql
#1.建立连接
db_config = {
user="root",
password="qwe123",
db="xiaoge",
charset="utf8"
}
with pymysql.connect(**db_config) as cursor:
#2.创建游标
#3.执行sql语句,返回受影响的行数
	#rows = cursor.execute("insert into student values(10,"xiaoge",18,"boy")
	#sql注入
	sql ="select * from student where name='%s' and age=%s"%("xiaoge","111 or 1=1")
	sql = "select * from student where name='%s' and age=%s"
	print(sql)
	#rows = cursor.execute(sql)
	rows = cursor.execute(sql,("xiaoge","111 or 1=1"))
	#安全的方式,不要自己拼接
	print(rows)
#4.获取结果
#获取一条
res = cursor.fetchone()
print(res)
exit()
#获取第二条
res1 = cursor.fetchone()
print(res1)
#获取后面的3条
res2 = cursor.fetchmany(3)
print(res2)
#获取剩下的所有
res3 = cursor.fetchall()
print(res3)

pymysql执行增删改查

#pymysql默认支持食物
import pymysql
db_config = {
"user":"root",
"password":"qwe123",
"db":"xiaoge",
"charset":"utf8"
}
conn = pymysql.connect(**db_config)
cursor = conn.cursor(pymysql.cursors.DictCursor)
try:
	sql = "select * from student where id=1"
	cursor.execute(sql)
	conn.commit()	#提交
	except Exception as e:
		print(e)
		conn.rollback()	#回滚

pymysql作业练习

形如图:

在这里插入图片描述
import pymysql
import random
import math
#数据库配置
db_config = {
“user”:“root”, #用户名
“password”:“qwe123”,
“db”:“xiaoge”, #数据库名
“port”:3306,
“charset”:“utf8” #字符编码
}
conn = pymysql.connect(**db_config)
cursor = cursor(cursor=pymysql.cursors.DictCursor)
def create_table():
#创建student表
try:
cursor.execute(“drop table if exists student”)
cursor.execute("""
create table student(
id int primary key auto_increment,
name varchar(32),
age tinyint)
“”")
print(“创建成功”)
except Exception as e:
print(“创建失败”)

def insert_data():
sql = "insert into student(name,age) values "
for i in range(100):
temp = ‘(“测试%s”,%s),’%(i,random,randint(18,50))
sql += temp
sql = sql[:-1]
try:
cursor.execute(sql)
conn.commit()
print(“插入成功”)
except Exception as e:
conn.rollback
print(“插入失败”)

def get_total_count():
#获取所有的记录条数
cursor.execute(“select count(id) as num from student”)
return cursor.fetchone()[“num”]

def select(page_num,page_size,total_num,max_page_num):
sql = “select * from student limit %s,%s”%((page_num-1)*page_size,page_size)
cursor.execute(sql)
res = cursor.fetchall()
info = “”"
±–±-------±-----+
| id | name| age |
±–±------±------+
“”"
for item in res:
temp = “|{id: ^3}|{name: ^8}|{age: ^6}|\n”.format(**item)
info += temp
floor = “±----±------±------+\n”
if page_num == 1:
botton = “总共%s页,第%s页,下一页(n)”%(max_page_num,page_num)
elif page_num == max_page_num:
bottom = “总共%s页,第%s页,上一页§”%(max_page_num,page_num)
else:
botton = “总共%s页,第%s页,上一页§,下一页(n)”%(max_page_num,page_num)
info = info + floor +botton
print(info)
if name==“main”:
total_num = get_total_count()
page_num = 1
page_size = 10
max_page_num = math.ceil(total_num/page_size)
while True:
select(page_num,page_size,total_num,max_page_num)
code = input(“请输入指令>>>>”)
if code == “n”:
if page_num<max_page_num:
page_num +=1
elif code == “p”:
if page_num>1:
page_num -= 1
elif code == “q”:
exit()

猜你喜欢

转载自blog.csdn.net/xiaogeldx/article/details/84768864
今日推荐