python访问mysql和redis
1. 修改mysql配置文件
修改bind-address=0.0.0.0(允许通过远程网络连接)


2. 修改redis配置文件
修改bind-address=0.0.0.0(允许通过远程网络连接),设置密码qwe123



3. 下载访问包pymysql和redis

4. 设置端口转发mysql和redis

5. 导入包pymysql连接mysql
import pymysql
mysql_connect_dict={
'host':'127.0.0.1',
'port':3333,
'user':'jianeng',
'password':'qwe123',
'db':'info',
'charset':'utf8'
}
# 连接数据库
conn = pymysql.connect(**mysql_connect_dict)
# 指定以dict形式返回,默认以元祖形式
#conn = pymysql.connect(**mysql_connect_dict,cursorclass=pymysql.cursors.DictCursor)
print(conn)
6. 访问mysql
1. 查询记录
# 创建游标
cursor = conn.cursor()
# sql查询语句
sql = "show databases"
# 执行sql,得到行数
row = cursor.execute(sql);
print('%s条数据'%row)
# 返回一条记录(元祖形式)
one = cursor.fetchone();
print(one)
# 返回多条记录(元祖形式)
many = cursor.fetchmany(3)
print(many)
# 返回所有记录(元祖形式)
all = cursor.fetchall()
print(all)
#循环输出
for al in all:
print(*al)
打印结果
6条数据
('information_schema',)
(('info',), ('mydb',), ('mysql',))
(('performance_schema',), ('sys',))
#循环结果
performance_schema
sys
2. 删除、创建表
dr_table ='drop table `user`'
# 删除表
cursor.execute(dr_table)
cr_table ='''create table if not exists user(
id int primary key auto_increment,
username varchar(20) not null,
password varchar(20) not null
)
'''
# 创建表
cursor.execute(cr_table)
3. 插入记录
# 插入数据
insertsql ='insert into user (username, password) VALUES (%s,%s)'
cursor.execute(insertsql,('zhangsan','123'))
# 插入多条(元祖形式)
cursor.executemany(insertsql,[('王五','qwq'),('赵四','123'),('千8','123')])
# 提交数据
conn.commit();
# sql查询语句
selectsql = "select * from user "
# 执行sql,得到行数
row = cursor.execute(selectsql);
print('返回%s条数据'%row)
# 返回所有记录(元祖形式)
select_all = cursor.fetchall();
print("select=",select_all)
打印结果
#返回4条数据
select= ((1, 'zhangsan', '123'), (2, '王五', 'qwq'), (3, '赵四', '123'), (4, '千8', '123'))
4. 修改记录
# 更新数据
updatesql='update user set username = %s where id=%s'
cursor.execute(updatesql,('张三','2'))
# 更新多条(元祖形式)
l = []
for x in range(1, 4):
l.append(('李%s'%x,str(x)))
cursor.executemany(updatesql,l)
# 提交数据
conn.commit();
# 执行sql,得到行数
row = cursor.execute(selectsql);
print('返回%s条数据'%row)
# 返回所有记录(元祖形式)
select_all = cursor.fetchall();
print("select=",select_all)
打印结果
#返回4条数据
select= ((1, '李1', '123'), (2, '李2', 'qwq'), (3, '李3', '123'), (4, '千8', '123'))
5. 删除记录
# 删除语句
deletesql='delete from user where id=%s'
cursor.execute(deletesql, 1)
# 删除多条
cursor.executemany(deletesql,[(2,),(3,)])
# 提交数据
conn.commit()
打印结果
#返回1条数据
select= ((4, '千8', '123'),)
7. 访问redis
import redis
import sys
import time
# 得到默认编码
print(sys.getdefaultencoding())
# 连接redis
re = redis.Redis(host='127.0.0.1', password='qwe123',port=5555)
# 设置name值
re.set('name',15)
print(type(re.get('name')))#byte类型(utf8格式16进制字节码)
if isinstance(re.get('name'), bytes):
# 字节码转换为字符串
print(re.get('name').decode('utf8'))
re.set('name','祖国')
# decode默认为utf8格式解码
print(re.get('name').decode())
# 设置过期时间为3s
re.set('name','祖国',ex=3)
time.sleep(3)
#打印过期后ttl
print(re.ttl('name'))
# 设置多个属性
re.mset(name='佳能',age='18')
print(re.mget('name','age'))
# 设置递增
re.incr('age')
print(re.get('age'))
re.incr('age',10)
print(re.get('age'))
# 删除序列的值c
re.lrem('test_list','c',0)
# 设置hash 值
re.hmset('userkey',{'name':'jianeng','age':'18'})
print(re.hgetall('userkey'))
打印结果
utf-8
<class 'bytes'>
15
祖国
None
[b'\xe4\xbd\xb3\xe8\x83\xbd', b'18']
b'19'
b'29'
{b'name': b'jianeng', b'pwd': b'123', b'age': b'18'}
redis终端输出中文

python访问mysql和redis的更多相关文章
- 06 python操作MySQL和redis(进阶)
python操作mysql.redis 阶段一.mysql事务 主要用于处理操作量大,复杂度高的数据.比如说,在人员管理系统中,你删除一个人员,你即需要删除人员的基本资料,也要删除和该人员相关的信息, ...
- Python访问MySQL(1):初步使用PyMySQL包
Windows 10家庭中文版,MySQL 5.7.20 for Win 64,Python 3.6.4,PyMySQL 0.8.1,2018-05-08 ---- 使用Python访问MySQL数据 ...
- python访问mysql
1,下载mysql-connector-python-2.0.4 pythoin访问mysql需要有客户端,这个就是连接mysql的库 解压后如下图: 双击lib 以windows为例 把mysql ...
- 利用Python访问Mysql数据库
首先要明确一点,我们在Python中需要通过第三方库才能访问Mysql. 有这样几种方式:Mysql-python(即MySQLdb).pymysql.mysql-connector.Mysql-py ...
- Python访问MySQL数据库并实现其增删改查功能
概述:对于访问MySQL数据库的操作,我想大家也都有一些了解.不过,因为最近在学习Python,以下就用Python来实现它.其中包括创建数据库和数据表.插入记录.删除记录.修改记录数据.查询数据.删 ...
- python学习道路(day12note)(mysql操作,python链接mysql,redis)
1,针对mysql操作 SET PASSWORD FOR 'root'@'localhost' = PASSWORD('newpass'); 设置密码 update user set password ...
- python 数据库mysql、redis及发送邮件
python 关系型数据库链接使用--mysql import pymysql # 引用mysql模块 # 创建连接,指定数据库的ip地址,账号.密码.端口号.要操作的数据库.字符集coon = py ...
- Python访问MySQL数据库
#encoding: utf-8 import mysql.connector __author__ = 'Administrator' config={'host':'127.0.0.1',#默认1 ...
- 【数据库】python访问mysql
import MySQLdb 所有的数据库遵循相同的python database API 需要建立connection对象连接数据库,之后建立cursor对象处理数据. conn = MySQLdb ...
随机推荐
- C#开发短信发送
//需要用到的命名空间 using System.Net;using System.IO;using System.Text;//调用时只需要把拼成的URL传给该函数即可.判断返回值即可public ...
- linux集群架构
Linux集群架构 根据功能划分为两大类:高可用和负载均衡 高可用集群通常为两台服务器,一台工作,另外一台作为冗余,当提供服务的机器宕机,冗余将接替继续提供服务 实现高可用的开源软件有:heart ...
- openvpn 客户端一键脚本安装
#!/bin/bash dir=/etc/openvpn#file=AD00012basepath=$(cd `dirname $0`; pwd)PACKAGE_DIR="${basepat ...
- EF数据迁移,未将对象引用设置到对象实例
现象: 执行Enable-Migrations -force时就报"未将对象引用设置到对象实例"的异常: DbProviderServicesExtensions.GetProvi ...
- 解决java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext这个问题
今天在运行别人的SSH项目时,遇到了这个问题 严重: Exception sending context initialized event to listener instance of class ...
- linux下lampp(xampp)安装memcached扩展
原理:根据自己的lampp中的php版本,编译memcache时,引用对应下载的php版本,并安装后的php_config来生成memcache.so文件,再将这个so文件放置到lamppp对应位置, ...
- bzoj 2288 【POJ Challenge】生日礼物 双向链表+堆优化
2288: [POJ Challenge]生日礼物 Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 1003 Solved: 317[Submit][ ...
- Spring mvc学习指南
使用flash attribute(闪存传值) 在配置文件中添加<mvc:annotion-driven/> 在controller方法参数里面添加RedirectAttributes r ...
- EmguCV 绘画图形
1.Image类中绘图常用函数列表 实践验证 ///初始化图片 private void Form1_Load(object sender, EventArgs e) { oldpic = new E ...
- CodeForces - 551C 二分+贪心
题意:有n个箱子形成的堆,现在有m个学生,每个学生每一秒可以有两种操作: 1: 向右移动一格 2: 移除当前位置的一个箱子 求移除所有箱子需要的最短时间.注意:所有学生可以同时行动. 思路:二分时间, ...