生成含年月日的mysql数据库备份文件

想在linux系统上做一个计划任务,每天23:59分左右对数据库进行备份,备份的文件名中包含当前时间的年月日(如:mydb-back-auto-20161109.sql)。

计划任务对应的执行文件如果用shell script写,比较简单,但是,由于是script的原因,代码都是可见的,对数据库进行备份,script中必定包含登录数据的账号和密码,所以利用script简便,但不安全。下面用C++写了一个。

mysqlbackup.cpp文件:

/*
* filenmae:mysqlbackup.cpp
*/
#include <iostream>
#include <ctime>
#include <sstream>
#include <string.h>
#include<stdlib.h>

using namespace std;

string datetimestr( )
{
   time_t now = time(0);

    tm *ltm = localtime(&now);
    ostringstream datetimeostr;
    ostringstream osYear,osYear1;
    ostringstream osMonth,osMonth1;
    ostringstream osDay,osDay1;
    ostringstream osHour,osHour1;
    ostringstream osMin,osMin1;
    ostringstream osSec,osSec1;

    osYear<< 1900 + ltm->tm_year;
    osMonth<< 1 + ltm->tm_mon;
    osDay<<  ltm->tm_mday ;
    osHour<<   ltm->tm_hour ;
    osMin<<  ltm->tm_min ;
    osSec<<  ltm->tm_sec;
    
    //如果月、时、分、秒的位数少于2位,则在前面补0;
    if (strlen(osMonth.str().c_str())<2)
	osMonth1<<"0"<<osMonth.str().c_str();
    else
        osMonth1<<osMonth.str().c_str();
 
    if (strlen(osDay.str().c_str())<2)
	osDay1<<"0"<<osDay.str().c_str();
    else
        osDay1<<osDay.str().c_str();

    if(strlen(osHour.str().c_str())<2)
	osHour1<<"0"<<osHour.str().c_str();
    else 
	osHour1<<osHour.str().c_str();

    if(strlen(osMin.str().c_str())<2)
	osMin<<"0"<<osMin.str().c_str();
    else
        osMin1<<osMin.str().c_str();
   
    if(strlen(osSec.str().c_str())<2)
	osSec1<<"0"<<osSec.str().c_str();
    else
        osSec1<<osSec.str().c_str();
    //datetimeostr<<osYear.str().c_str()<<osMonth1.str().c_str()<<osDay1.str().c_str()<<osHour1.str().c_str()<<osMin1.str().c_str()<<osSec1.str().c_str();
    
    datetimeostr<<osYear.str().c_str()<<osMonth1.str().c_str()<<osDay1.str().c_str();
    return datetimeostr.str();//返回当前年月日的字符串,如20161109
}

int main(){
    ostringstream osfilename,oscommand;
    osfilename<<"mydb-back-auto-"<<datetimestr()<<".sql";//构造mysql备份文件的文件名;如:mydb-back-auto-20161109.sql
    oscommand<<"mysqldump -uroot -p123456 --compact mydb2 >"<<osfilename.str();
    system(oscommand.str().c_str());

}

源码下载地址: https://github.com/yangboduan/mysqlbackup

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值