python管理mysql(实现读写分离)及如何用Mycat读写分离

Day24  

编写python代码实现读写分离

1、安装pymysql,它是python管理mysql的驱动,或者称为连接器

[root@pyhton ~]#pip3 config set global.index-url Simple Index

[root@python ~]# pip3 install pymysql   #安装pymysql

[root@pyhton ~]# python3

Python 3.6.8

[root@pyhton ~]# yum -y install pymysql

2、编写rwsplit.py文件

# 引入模块 python链接mysql工具,驱动包,连接器

import pymysql

# python 类 类名 rwsplit,名字可以和文件名不一致

# 三个函数,函数的标识 def 函数名 (self,参数列表):

# __init__ 初始化函数,构造函数,在这个类被实例的时候,执行__init__函数

# master_statment 自定义函数,根据实际需要,开发或者运维自己定义的函数

# slave_statement 自定义函数,根据实际需要,自定

class rwsplit(object):

# 构造函数

# 1.在屏幕上输出了 initialized

# 2.创建了全局变量master_conn

# 3.创建了全局变量slave_conn

# 4.全局变量可以在其他的函数中进行调用和修改

# 5.为什么要在init函数中创建全局变量,因为init在rwsplit类被实例的同时执行

def __init__ (self):

print("initialized")

self.master_conn=pymysql.connect(

host="10.1.1.11",

user="zhangmin",

password="zhangmin",

database="test",

port=3306

)

self.slave_conn=pymysql.connect(

host="10.1.1.12",

user="zhangmin",

password="zhangmin",

database="test",

port=3310

)

# 输出serverid,执行sql语句,增删改查

def master_statment(self,sql):

cursor=self.master_conn.cursor()

cursor.execute("show variables like 'server_id'")

print(cursor.fetchall())

print(cursor.execute(sql))

self.master_conn.commit()

# 执行查询操作

def slave_statment(self,sql):

cursor=self.slave_conn.cursor()

cursor.execute(sql)

print(cursor.fetchall())

# 入口

if __name__ == "__main__":

# 实例rwsplit

demo=rwsplit()

# 要求用户输入一个sql语句

sql=input("sign sql:")

#判断sql

if sql[:6]=="select" or sql[:4]=="show":

demo.slave_statment(sql)

else:

demo.master_statment(sql)

从服务器登录mysql 8.x遇到的问题(每次要获取公钥)之解决方案

[root@salve_mysql ~]# help change master

# Get_master_public_key: 1/0   【自动获取/不自动获取】

[root@salve_mysql ~]#mysql -uroot -p

Enter password:Juan@1888$

mysql> show slave status\G

# 先停用slave服务

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值