python 实现mysql自动增删分区的方法

连接mysql

#!/usr/bin/python
#-*- coding:utf-8 -*-

import time
import pymysql

class connect_mysql(object):
  def __init__(self, host, dbname):
    self.mysql_config = {
      'host': host,
      'port': 33071,
      'user': 'sysbench',
      'passwd': '970125',
      'db': dbname,
      'charset': 'utf8mb4',
    }
    self.dbname = dbname

  def select_db(self, sql):
    mysql_conn = pymysql.connect(**self.mysql_config)
    try:
      query = "%s" %(sql)
      cur = mysql_conn.cursor()
      cur.execute(query)
      results = cur.fetchall()
      cur.close()
      mysql_conn.close()
      return results
    except Exception as err:
      print(err)

  def excute_db(self, sql):
    mysql_conn = pymysql.connect(**self.mysql_config)
    try:
      cur = mysql_conn.cursor()
      cur.execute(sql)
      mysql_conn.commit()
      cur.close()
      mysql_conn.close()
      return 0
    except Exception as err:
      mysql_conn.rollback()
      print(err)

增删分区

#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
import pymysql
import importlib
import logging
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from connect_db_forbatch import connect_mysql

def incr_partition():
  print("新增分区...")
  max_partition_sql = "SELECT REPLACE(partition_name,'p','') FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA='%s' and table_name='%s' ORDER BY partition_ordinal_position DESC LIMIT 1;" %(db_name,table_name)
#  print(max_partition_sql)
  max_partition = connect_mysql(host,db_name).select_db(max_partition_sql)
  max_date = str(max_partition[0][0])
  max_partition_name = (datetime.strptime(max_date, "%Y%m%d") + relativedelta(days=1)).strftime("%Y%m%d")
  max_partition_value = (datetime.strptime(max_date, "%Y%m%d") + relativedelta(days=2)).strftime("'%Y-%m-%d'")
  alter_max_partition_sql = "ALTER TABLE %s.%s ADD PARTITION (PARTITION p%s VALUES LESS THAN (to_days(%s)) ENGINE = InnoDB);" %(db_name,table_name,max_partition_name,max_partition_value)
  print(alter_max_partition_sql)
  connect_mysql(host,db_name).excute_db(alter_max_partition_sql)

def del_partition():
  print("删除分区...")
  min_partition_sql = "SELECT REPLACE(partition_name,'p','') FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA='sbtest' and table_name='t1' ORDER BY partition_ordinal_position LIMIT 1;"
#  print(min_partition_sql)
  min_partition = connect_mysql(host,db_name).select_db(min_partition_sql)
  min_date = str(min_partition[0][0])
  min_partition_name = (datetime.strptime(min_date, "%Y%m%d") + relativedelta(days=0)).strftime("%Y%m%d")
  alter_min_partition_sql = "ALTER TABLE %s.%s DROP PARTITION p%s;" %(db_name,table_name,min_partition_name)
  print(alter_min_partition_sql)
  connect_mysql(host,db_name).excute_db(alter_min_partition_sql)

if __name__ == "__main__":
  host = sys.argv[1]
  db_name = sys.argv[2]
  table_name = sys.argv[3]
  incr_partition()
  del_partition()

到此这篇关于python 实现mysql自动增删分区的方法的文章就介绍到这了,更多相关python mysql自动增删分区内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python连接mysql数据库及简单增删改查操作示例代码

    1.安装pymysql 进入cmd,输入 pip install pymysql: 2.数据库建表 在数据库中,建立一个简单的表,如图: 3.简单操作 3.1查询操作 #coding=utf-8 #连接数据库测试 import pymysql #打开数据库 db = pymysql.connect(host="localhost",user="root",password="root",db="test") #使用cursor

  • 详解使用pymysql在python中对mysql的增删改查操作(综合)

    这一次将使用pymysql来进行一次对MySQL的增删改查的全部操作,相当于对前五次的总结: 先查阅数据库: 现在编写源码进行增删改查操作,源码为: #!/usr/bin/python #coding:gbk import pymysql from builtins import int #将MysqlHelper的几个函数写出来 def connDB(): #连接数据库 conn=pymysql.connect(host="localhost",user="root&quo

  • python实现的MySQL增删改查操作实例小结

    本文实例总结了python实现的MySQL增删改查操作.分享给大家供大家参考,具体如下: 代码片段一 连接并执行sql #encoding:UTF-8 import MySQLdb conn = MySQLdb.Connect( host = '127.0.0.1', port = 3306, user = 'root', passwd='123456', db='imooc', charset='utf8' ) cursor = conn.cursor() print conn print c

  • Python使用pymysql模块操作mysql增删改查实例分析

    本文实例讲述了Python使用pymysql模块操作mysql增删改查.分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- import pymysql user = input('请输入用户名:') pwd = input('请输入密码:') # 1.连接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123', db='t1', charset='utf8')

  • python django 增删改查操作 数据库Mysql

    下面介绍一下django增删改查操作: 1.view.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from polls.models import Test from django.shortcuts import render # Create your views here. # 解决乱码 import sys reload(sy

  • Python操作MySQL数据库实例详解【安装、连接、增删改查等】

    本文实例讲述了Python操作MySQL数据库.分享给大家供大家参考,具体如下: 1.安装 通过Python连接MySQL数据库有很多库,这里使用官方推荐的MySQL Connector/Python库,其官网为:https://dev.mysql.com/doc/connector-python/en/. 通过pip命令安装: pip install mysql-connector-python 默认安装的是最新的版本,我安装的是8.0.17,对应MySQL的8.0版本.MySQL统一了其相关

  • python Django连接MySQL数据库做增删改查

    1.下载安装MySQLdb类库http://www.djangoproject.com/r/python-mysql/2.修改settings.py 配置数据属性 复制代码 代码如下: DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.        'NAME': 'djang

  • Python实现MySQL操作的方法小结【安装,连接,增删改查等】

    本文实例讲述了Python实现MySQL操作的方法.分享给大家供大家参考,具体如下: 1. 安装MySQLdb.从网站下载Mysql for python 的package 注意有32位和64位之分. 2. 安装完成之后从Python IDLE 导入MySQLdb >>>import MySQLdb 3. 新建一个数据库连接: >>>conn =MySQLdb.connect(host = '127.0.0.1',user= 'root',passwd='123456'

  • Python操作mysql数据库实现增删查改功能的方法

    本文实例讲述了Python操作mysql数据库实现增删查改功能的方法.分享给大家供大家参考,具体如下: #coding=utf-8 import MySQLdb class Mysql_Oper: def __init__(self,host,user,passwd,db): self.host=host self.user=user self.passwd=passwd self.database=db def db_connecet(self): try: #连接 conn=MySQLdb.

  • python连接mysql数据库示例(做增删改操作)

    一.相关代码数据库配置类 MysqlDBConn.py 复制代码 代码如下: #encoding=utf-8'''Created on 2012-11-12 Mysql Conn连接类''' import MySQLdb class DBConn: conn = None #建立和数据库系统的连接    def connect(self):        self.conn = MySQLdb.connect(host="localhost",port=3306,user="

随机推荐