목차
需求
代码
데이터 베이스 MySQL 튜토리얼 [Mysql]备份同库中一张表的历史记录insertinto..select_MySQL

[Mysql]备份同库中一张表的历史记录insertinto..select_MySQL

Jun 01, 2016 pm 12:59 PM
역사 지원

需求

现在有个这么一个需求,mysql中有个表,数据增长的很快,但是呢这个数据有效期也就是1个月,一个月以前的记录不太重要了,但是又不能删除。为了保证这个表的查询速度,需要一个简单的备份表,把数据倒进去。

代码

于是我写了一个小脚本,用来做定时任务,把这个表某段时间的数据备份到备份表中,核心就是个简单的sql。

原始表radius 备份的表为 radius2015

<code class="hljs python">#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#python2.7x
#authror: orangleliu
#备份radius中的上网记录表,每个月备份一次,原始表中保留一份数据
#使用同一个数据库中的一个不同表名的表备份

import time
import datetime
import logging
from datetime import timedelta

import MySQLdb
import MySQLdb.cursors


logging.basicConfig(format=&#39;%(asctime)s %(levelname)s - \
    %(message)s&#39;)
logger = logging.getLogger(&#39;backup&#39;)
logger.setLevel(logging.DEBUG)

#数据库配置
DBPARAMS = {
    "host":"127.0.0.1",
    "user":"root",
    "password":"",
    "database":"test",
    "charset": ""
}

#这里使用select into 来备份,数据校验对比记录数,一个月大概100w条数据
#radacct2015
#检查表,检查重传,备份,校验

create_table_sql = &#39;&#39;&#39;
CREATE TABLE `{0}` (
  `radacctid` bigint(21) NOT NULL AUTO_INCREMENT,
  `acctsessionid` varchar(64) NOT NULL DEFAULT &#39;&#39;,
  `acctuniqueid` varchar(32) NOT NULL DEFAULT &#39;&#39;,
  `username` varchar(64) NOT NULL DEFAULT &#39;&#39;,
  `groupname` varchar(64) NOT NULL DEFAULT &#39;&#39;,
  `realm` varchar(64) DEFAULT &#39;&#39;,
  `nasipaddress` varchar(15) NOT NULL DEFAULT &#39;&#39;,
  `nasportid` varchar(15) DEFAULT NULL,
  `nasporttype` varchar(32) DEFAULT NULL,
  `acctstarttime` int(11) DEFAULT NULL,
  `acctupdatetime` int(11) DEFAULT NULL,
  `acctstoptime` int(11) DEFAULT NULL,
  `acctinterval` int(12) DEFAULT NULL,
  `acctsessiontime` int(12) unsigned DEFAULT NULL,
  `acctauthentic` varchar(32) DEFAULT NULL,
  `connectinfo_start` varchar(50) DEFAULT NULL,
  `connectinfo_stop` varchar(50) DEFAULT NULL,
  `acctinputoctets` bigint(20) DEFAULT NULL,
  `acctoutputoctets` bigint(20) DEFAULT NULL,
  `calledstationid` varchar(50) NOT NULL DEFAULT &#39;&#39;,
  `callingstationid` varchar(50) NOT NULL DEFAULT &#39;&#39;,
  `acctterminatecause` varchar(32) NOT NULL DEFAULT &#39;&#39;,
  `servicetype` varchar(32) DEFAULT NULL,
  `framedprotocol` varchar(32) DEFAULT NULL,
  `framedipaddress` varchar(15) NOT NULL DEFAULT &#39;&#39;,
  PRIMARY KEY (`radacctid`),
  UNIQUE KEY `acctuniqueid` (`acctuniqueid`),
  KEY `username` (`username`),
  KEY `framedipaddress` (`framedipaddress`),
  KEY `acctsessionid` (`acctsessionid`),
  KEY `acctsessiontime` (`acctsessiontime`),
  KEY `acctstarttime` (`acctstarttime`),
  KEY `acctinterval` (`acctinterval`),
  KEY `acctstoptime` (`acctstoptime`),
  KEY `nasipaddress` (`nasipaddress`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
&#39;&#39;&#39;


back_sql = &#39;&#39;&#39;
INSERT INTO {0}
SELECT *
FROM {1}
WHERE acctstarttime < UNIX_TIMESTAMP(
   STR_TO_DATE(&#39;{2}&#39;, &#39;%Y-%m-%d&#39;)
) AND acctstarttime >= UNIX_TIMESTAMP(
   STR_TO_DATE(&#39;{3}&#39;, &#39;%Y-%m-%d&#39;)
)&#39;&#39;&#39;


count_sql = """
SELECT count(*) FROM {0} WHERE 1=1 AND
acctstarttime < UNIX_TIMESTAMP(
   STR_TO_DATE(&#39;{1}&#39;, &#39;%Y-%m-%d&#39;)
) AND acctstarttime >= UNIX_TIMESTAMP(
   STR_TO_DATE(&#39;{2}&#39;, &#39;%Y-%m-%d&#39;)
)
"""


#date tools
def get_year(month):
    #month like 201505
    return datetime.datetime.strptime(month, "%Y%m").year


def get_month_firstday_str(month):
    return datetime.datetime.strptime(month,"%Y%m").\
                                        strftime("%Y-%m-%d")

def get_next_month_firstday_str(month):
    month_firstday = datetime.datetime.strptime(month,"%Y%m")
    monthnum = month_firstday.month
    return "{0}-{1}-{2}".format(
            month_firstday.year if monthnum < 12 else \
                                 month_firstday.year + 1,
            monthnum + 1 if monthnum < 12 else 1, 1)


class DBConn(object):
    __CONFIG = {
        &#39;default&#39;: {
            &#39;host&#39;: "",
            &#39;user&#39;: "",
            &#39;database&#39;: "",
            &#39;password&#39;: "",
            &#39;charset&#39;: "",
        }
    }

    def __init__(self, connname=&#39;&#39;, connconfig={}):
        if connconfig:
            self.connconfig = connconfig
        else:
            connname = connname or &#39;default&#39;
            self.connconfig = self.__CONFIG.get(connname, &#39;default&#39;)
        self.conn = None

    def __enter__(self):
        try:
            self.conn = MySQLdb.connect(
                user=self.connconfig[&#39;user&#39;],
                db=self.connconfig[&#39;database&#39;],
                passwd=self.connconfig[&#39;password&#39;],
                host=self.connconfig[&#39;host&#39;],
                use_unicode=True,
                charset=self.connconfig[&#39;charset&#39;] or "utf8",
                #cursorclass=MySQLdb.cursors.DictCursor
                )

            return self.conn
        except Exception, e:
            print str(e)
            return None

    def __exit__(self, exe_type, exe_value, exe_traceback):
        if exe_type and exe_value:
            print &#39;%s: %s&#39; % (exe_type, exe_value)
        if self.conn:
            self.conn.close()


class RadiusBackup(object):
    def __init__(self, month, conn):
        self.conn = conn
        self.cursor = conn.cursor()
        self.month = month
        self.year = get_year(month)
        self.month_firstday = get_month_firstday_str(month)
        self.next_month_firstday = get_next_month_firstday_str(month)
        self.tablename = "radacct{0}".format(self.year)
        self.stable = "radacct"


    def check_table_exist(self):
        check_table_sql = "SHOW TABLES LIKE &#39;{0}&#39;".format(
                            self.tablename)
        self.cursor.execute(check_table_sql)
        res = self.cursor.fetchall()
        return True if len(res) > 0 else False


    def create_backup_table(self):
        sql = create_table_sql.format(self.tablename)
        self.cursor.execute(sql)
        logger.info(u"开始创建备份表 {0}".format(self.tablename))


    def check_datas_count(self, tablename):
        sql = count_sql.format(tablename, self.next_month_firstday,
                    self.month_firstday)
        logger.debug(sql)
        self.cursor.execute(sql)
        res = self.cursor.fetchone()
        return res[0]


    def check_before(self):
        flag = False
        #check table
        if not self.check_table_exist():
            self.create_backup_table()
            if self.check_table_exist() == False:
                logger.error(u"无法找到备份表 exit")
                return flag
        #check datas
        if self.check_datas_count(self.tablename) > 0:
            return flag
        else:
            return True


    def backup_datas(self):
        sql = back_sql.format(self.tablename, self.stable,
                self.next_month_firstday, self.month_firstday)
        logger.debug(sql)
        self.cursor.execute(sql)
        self.conn.commit()


    def check_after(self):
        snum = self.check_datas_count(self.stable)
        bnum = self.check_datas_count(self.tablename)
        if snum > 0 and (snum == bnum):
            logger.info(u"备份成功")
            return snum, True
        else:
            return -1, False

    def backup_handler(self):
        if self.check_before():
            logger.info(u"检查完毕,开始备份数据")
            self.backup_datas()
            logger.info(u"开始备份")
            num, flag = self.check_after()
            logger.info(u"本次备份{0} 数据 {1}条".format(self.month, num))
        else:
            logger.info(u"数据已经有备份,请检查")


if __name__ == "__main__":
    month = "201504"

    with DBConn(connconfig=DBPARAMS) as dbconn:
        if dbconn:
            backup = RadiusBackup(month, dbconn)
            backup.backup_handler()
        else:
            logger.error("can not connect to db")</code>
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Mingtide 침몰 역사 속의 5개 등대의 위치 소개 Mingtide 침몰 역사 속의 5개 등대의 위치 소개 Mar 07, 2024 pm 03:58 PM

가라앉는 조수의 역사 퀘스트에서 등대 5개를 찾고 계시나요? 이 가이드는 이러한 등대가 어디에서 발견되기를 기다리고 있는지에 대한 자세한 설명을 제공합니다. 이것이 필요한 등대를 빠르게 찾고 임무를 성공적으로 완료하는 데 도움이 되기를 바랍니다! Mingtide Five Lighthouse의 침몰 역사를 소개하고 구체적인 위치를 나열합니다. 1. 첫 번째 등대 : Beiluoye 바로 위에 위치한 불모의 돌고원으로 가십시오. 2. 두 번째 등대: 다음으로 북동쪽 순간이동 지점 주변에 있는 Zhongqu 플랫폼으로 이동하세요. 3. 세 번째 등대: 후커우산 남동쪽으로 이동하여 우밍만(Wuming Bay)을 따라 찾으세요. 4. 네번째 등대 : 앵그리버드 지 남동쪽 끝 절벽 근처 순간이동 지점으로 가주세요. 5. 다섯 번째 등대: 빛 없는 숲의 첫 번째 침묵 구역으로 이동하면 절벽 가장자리에 있습니다.

Chrome 확장 프로그램을 백업하는 방법 Chrome 확장 프로그램을 백업하는 방법 Jan 30, 2024 pm 12:36 PM

Chrome 확장 프로그램을 백업하는 방법은 무엇입니까? 대부분의 Google Chrome 사용자의 경우 일상적인 사용 중에 어느 정도의 플러그인이 설치됩니다. 플러그인이 있으면 사용 환경이 향상될 수 있습니다. 시스템이나 브라우저를 다시 설치하면 이러한 플러그인은 유지되지 않으며, 다시 다운로드하여 설치해야 하는 번거로움이 있습니다. 그렇다면 현재 설치된 플러그인을 백업할 수 있는 방법이 있습니까? 방법은 다음과 같습니다. 크롬 플러그인을 백업하는 튜토리얼 방법은 먼저 구글 크롬을 열고 오른쪽 상단 메뉴를 클릭한 뒤 도구 더보기 - 확장 프로그램을 선택한다. 확장 페이지 위에서 패키지 확장을 클릭합니다. C:UsersAdministratorAppDataLocalGoogleChromeUserDataDe

Windows 11의 파일 탐색기에서 시작 백업을 삭제하는 방법 Windows 11의 파일 탐색기에서 시작 백업을 삭제하는 방법 Feb 18, 2024 pm 05:40 PM

Windows 11의 파일 탐색기에서 "백업 시작" 옵션을 숨기려면 다음을 수행하십시오. 파일 탐색기에서 시작 백업 옵션을 비활성화하거나 숨기는 방법에는 여러 가지가 있으며, 이 작업을 신속하게 수행하는 데 도움이 되는 몇 가지 방법을 간략하게 나열하겠습니다. 시작하기 전에 이 옵션이 OneDrive와 밀접하게 연결되어 있다는 점을 이해해야 합니다. 라이브러리 폴더(예: 문서, 그림, 음악 등)를 열면 파일 탐색기 경로에 즉시 나타납니다. Windows 11 파일 탐색기에서 시작 백업을 삭제하는 방법 Windows 11 파일 탐색기에서 시작 백업을 삭제하려면 다음 단계를 따르세요.

PHP에서 MySQL 백업 및 복원을 사용하는 방법은 무엇입니까? PHP에서 MySQL 백업 및 복원을 사용하는 방법은 무엇입니까? Jun 03, 2024 pm 12:19 PM

PHP에서 MySQL 데이터베이스를 백업하고 복원하는 작업은 다음 단계에 따라 수행할 수 있습니다. 데이터베이스 백업: mysqldump 명령을 사용하여 데이터베이스를 SQL 파일로 덤프합니다. 데이터베이스 복원: mysql 명령을 사용하여 SQL 파일에서 데이터베이스를 복원합니다.

삭제된 호스트 파일을 복원하는 방법 삭제된 호스트 파일을 복원하는 방법 Feb 22, 2024 pm 10:48 PM

제목: 호스트 파일 삭제 후 복원 방법 요약: 호스트 파일은 운영체제에서 매우 중요한 파일로 도메인 이름을 IP 주소에 매핑하는 데 사용됩니다. 실수로 호스트 파일을 삭제한 경우 특정 웹 사이트에 액세스하지 못하거나 기타 네트워크 문제가 발생할 수 있습니다. 이 문서에서는 Windows 및 Mac 운영 체제에서 실수로 삭제된 호스트 파일을 복구하는 방법을 소개합니다. 텍스트: 1. Windows 운영 체제에서 호스트 파일을 복원합니다.

Linux 명령 기록을 보고 관리하는 방법 Linux 명령 기록을 보고 관리하는 방법 Aug 01, 2023 pm 09:17 PM

Linux에서 명령 기록을 보는 방법 Linux에서는 이전에 실행된 모든 명령 목록을 보려면 History 명령을 사용합니다. 이것은 매우 간단한 구문을 가지고 있습니다:historyhistory 명령과 쌍을 이루는 일부 옵션은 다음과 같습니다. 옵션 설명 -c는 현재 세션에 대한 명령 기록을 지웁니다. -w는 명령 기록을 파일에 기록합니다. -r은 기록 파일에서 명령 기록을 다시 로드합니다. n 최근 명령의 출력 수 제한 Linux 터미널에서 이전에 실행된 모든 명령 목록을 보려면 간단히 History 명령을 실행하십시오. 명령 기록을 보는 것 외에도 명령 기록을 관리하고 이전에 실행한 명령에 대한 수정을 수행할 수도 있습니다. 명령 기록을 검색하거나 기록을 완전히 삭제할 수도 있습니다.

Windows 서버 백업을 설치, 제거 및 재설정하는 방법 Windows 서버 백업을 설치, 제거 및 재설정하는 방법 Mar 06, 2024 am 10:37 AM

WindowsServerBackup은 WindowsServer 운영 체제와 함께 제공되는 기능으로, 사용자가 중요한 데이터 및 시스템 구성을 보호하고 중소기업 및 대기업 수준의 기업에 완벽한 백업 및 복구 솔루션을 제공하도록 설계되었습니다. Server2022 이상을 실행하는 사용자만 이 기능을 사용할 수 있습니다. 이 문서에서는 WindowsServerBackup을 설치, 제거 또는 재설정하는 방법을 설명합니다. Windows Server 백업을 재설정하는 방법 서버 백업에 문제가 있거나 백업에 너무 오랜 시간이 걸리거나 저장된 파일에 액세스할 수 없는 경우 Windows Server 백업 설정을 재설정하는 것을 고려할 수 있습니다. Windows를 재설정하려면

고스트-고스트 백업 튜토리얼로 시스템을 백업하는 방법 고스트-고스트 백업 튜토리얼로 시스템을 백업하는 방법 Mar 06, 2024 pm 04:30 PM

최근 많은 친구들이 편집자에게 ghost를 사용하여 시스템을 백업하는 방법을 문의했습니다. 다음으로 ghost를 사용하여 시스템을 백업하는 방법에 대한 튜토리얼을 배워보겠습니다. 모두에게 도움이 되기를 바랍니다. 1. Ghost를 실행한 후 그림과 같이 "확인"을 클릭하세요. 2. 그림과 같이 "로컬" → "파티션" → "이미지로"(의미: 로컬 → 파티션 → 이미지 파일로)를 클릭합니다. 3. 로컬 하드 디스크 선택 창이 나타나면 그림과 같이 백업할 파티션이 있는 하드 디스크를 클릭한 후 "확인"을 클릭하세요. 4. 소스 파티션 선택 창이 나타나면(소스 파티션은 백업하려는 파티션입니다) 시스템이 있는 파티션(일반적으로 영역 1, 올바르게 선택해야 함)을 클릭한 다음 "확인"을 클릭합니다. , 그림에 표시된 것처럼. 5. 이때 플레이

See all articles