Python与数据库交互
DB-API
MySQL
原理:
db_config = {
'host': '127.0.0.1', # 需要连接ip
'port': 3306, # 默认端口3306
'user': 'root', # 用户名.
'password': 'lls114', # 用户密码
'db': 'python3', # 进入的数据库名.
'charset': 'utf8' # 编码方式.
}
使用步骤:
1:导入模块:import pymysql
2:建立连接:pymysql.connect(**dbconfig)
连接是不能操作数据库的,需要用连接生成游标来操作
3:创建游标: connection.cursor()
4:执行SQL语句:cursor. Execute(sq.)
5:获取结果:cur.fetchall()
Eg:
import pymysql
“”"
a = {‘name’: ‘g1’, ‘age’: 18}
**a
func(**a)
func(name=‘g1’, age=18) # 解包
pymysql这个库实现了事务.
“”"
db_config = {
'host': '127.0.0.1', # 需要连接ip
'port': 3306, # 默认端口3306
'user': 'root', # 用户名.
'password': 'lls114', # 用户密码
'db': 'python3', # 进入的数据库名.
'charset': 'utf8' # 编码方式.
}
conn = pymysql.connect(**db_config)
cur = conn.cursor() # create cursor.
try:
sq. = 'INSERT INTO students VALUE (2, "Jack")'
# sq. = 'SELECT * FROM students'
rv = cur.execute(sq.) # execute, rv接收行数.
resp = cur.fetchall() # 接收展示内容.
[print(entry) for entry in resp]
except Exception as e:
print(e)
conn.rollback() # 相当于撤销, 如果失败就回滚.
finally:
conn.commit() # 提交修改的数据.
cur.close() # 关闭游标.
conn.close() # 关闭conn.
Redis
1:安装python包redis: pip install redis
2:连接redis:Redis.StrictRedis()
3:在程序操作的数据为bytes类型,加入decode_responses=True,写入的数据为str类型
Eg:
import redis
“”"
10060
(你的电脑能够ping到我们虚拟机ip.)
1. 把虚拟机的防火墙的6379打开. sudo ufw allow 6379
2. redis服务的配置信息.
sudo vim /etc/redis/redis.conf
bind 0.0.0.0
sudo /etc/init.d/redis-server restart
“”"
red = redis.StrictRedis(host='192.168.75.250', port=6379, decode_responses=True)
print(red.keys())
red.set('name', 'Jack')
red.append('name', ' Lee')
print(red.type('name'))
# red.delete('name')
print(red.get('name'))
print(red.exists('name'))
red.mset({'mname1': 'Jack1', 'mname2': 'Jack2'})
print(red.mget('mname1', 'mname2'))
print(red.expire('name', 10))
print(red.ttl('name'))
print(red.set('exname', 'haha', 20))
print(red.ttl('exname'))
red.rename('exname', 'new_ex_name')
print(red.keys())
red.delete('list_name')
red.lpush('list_name', 'g1', 'g2', 'g3')
red.rpush('list_name', 'g4', 'g5', 'g6')
red.lrem('list_name', 0, 'g1')
print(red.lrange('list_name', 0, -1))
red.hset('hash_name', 'name', 'Jack')
print(red.hget('hash_name', 'name'))
red.hmset('hash_name', {'name1': 'Jack1', 'name2': 'Jack2'})
print(red.hmget('hash_name', 'name', 'name1', 'name2'))
print(red.hgetall('hash_name'))
red.sadd('set_name', 1, 2, 3, 1, 2)
print(red.smembers('set_name'))
red.zadd('zset_name', 10, 'g1', 20, 'g2', 30, 'g3', 40, 'g3')
print(red.zrange('zset_name', 0, -1))
print(red.flushdb())
注:与在python使用的三个不同点
delete
mset
hmset