DB-API
Mysql
Redis
连接mysql
db_config = {
‘user’:'root',
'password':'qwe123',
'db':'数据库名',
'charset':'utf8' //不是utf-8
}
使用步骤:
import pymysql
建立连接:connection = pymysql.connect(**db_config)
获取游标:cursor = connection.cursor()
正常的增删改查操作:cursor.execute('select * from stu') //sql语句不用";"结束
cursor.execute('insert into stu values(1,1,'yu'),(2,3,'wang')') //执行完之后要cursor.execute('commit')才行,不然在ubuntu终端看不到更新的数据
获取结果:res = cursor.fetchall()
别忘了关闭游标和连接:cursor.close() connection.close()
上下文管理器:
with connection.cursor() as cursor:
正常的增删改查操作
connection.close()
redis
python与redis交互几乎和redis数据库操作一样
安装python包redis:pip install redis
连接redis:redis.Redis() //为了兼容旧版本(不推荐使用)
连接redis: connection = redis.StrictRedis(db = 2,decode_response = True) db=2:redis2号数据库 decode_response = True 数据传输的是string格式,而非二进制的数据
#str
# res = conn.get('num')
# conn.set('name','wl')
# #list
# conn.rpush('li',1,2,3)
# res=conn.lrange('li',0,10)
# conn.lrem('li',0,1)
# print(res)
#hash
# conn.hset('hash_1','age',1)
# res = conn.hget('hash_1','age')
# print(res)
#set
# conn.sadd('set',1,3,5,7,9)
# res = conn.smembers('set')
# conn.srem('set',1)
# print(res)
#zset
# conn.zadd('zset',1,2,2,5,6,0,4,9,0,8)
# res = conn.zrange('zset',0,10)
# print(res)