怎么用java备份mysql数据库?

怎么用java备份mysql数据库?,第1张

首先,设置mysql的环境变量(在path中添加%MYSQL_HOME%\bin),重启电脑。

完整代码:

备份

public static void main(String[] args) {

backup()

load()

}

public static void backup() {

try {

Runtime rt = Runtime.getRuntime()

// 调用 mysql 的 cmd:

Process child = rt

.exec("mysqldump -u root --set-charset=utf8 bjse act_obj")// 设置导出编码为utf8。这里必须是utf8

// 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行

InputStream in = child.getInputStream()// 控制台的输出信息作为输入流

InputStreamReader xx = new InputStreamReader(in, "utf8")// 设置输出流编码为utf8。这里必须是utf8,否则从流中读入的是乱码

String inStr

StringBuffer sb = new StringBuffer("")

String outStr

// 组合控制台输出信息字符串

BufferedReader br = new BufferedReader(xx)

while ((inStr = br.readLine()) != null) {

sb.append(inStr + "\r\n")

}

outStr = sb.toString()

// 要用来做导入用的sql目标文件:

FileOutputStream fout = new FileOutputStream(

"e:/mysql-5.0.27-win32/bin/bjse22.sql")

OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8")

writer.write(outStr)

// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免

writer.flush()

// 别忘记关闭输入输出流

in.close()

xx.close()

br.close()

writer.close()

fout.close()

System.out.println("")

} catch (Exception e) {

e.printStackTrace()

}

}

public static void load() {

try {

String fPath = "e:/mysql-5.0.27-win32/bin/bjse22.sql"

Runtime rt = Runtime.getRuntime()

// 调用 mysql 的 cmd:

Process child = rt.exec("mysql -u root bjse ")

OutputStream out = child.getOutputStream()//控制台的输入信息作为输出流

String inStr

StringBuffer sb = new StringBuffer("")

String outStr

BufferedReader br = new BufferedReader(new InputStreamReader(

new FileInputStream(fPath), "utf8"))

while ((inStr = br.readLine()) != null) {

sb.append(inStr + "\r\n")

}

outStr = sb.toString()

OutputStreamWriter writer = new OutputStreamWriter(out, "utf8")

writer.write(outStr)

// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免

writer.flush()

// 别忘记关闭输入输出流

out.close()

br.close()

writer.close()

System.out.println("")

} catch (Exception e) {

e.printStackTrace()

}

}

备份语句:

mysql>SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',

' from db_testtemp where std_state='1'

Query OK, 1 row affected (0.00 sec)

mysql>SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',

' from db_testtemp

Query OK, 2 rows affected (0.00 sec)

只生成一个只有数据的.txt:SELECT * INTO OUTFILE "D:\\data\\db_testtemp.txt" fields terminated by ',' lines terminated by '\r\n' from db_testtemp

只生成一个只有数据的.txt:mysqldump -uroot -pncae2010 -w "std_state='1'" -T D:\data --no-create-info --fields-terminated-by=, exam db_testtemp

生成一个创建数据库语句的.sql,一个只有数据的.txt:mysqldump -uroot -pncae2010 -w "std_state='1'" -T D:\data --fields-terminated-by=, exam db_testtemp

只生成insert语句:mysqldump -uroot -pncae2010 -w "std_state='1'" -t exam db_testtemp >D:\data\a.sql

第步:我数据库备份某目录注明间:

运行备份脚本(注意备份目录我/home/dbback/)

查看目录否备份文件细同能发现我mysqldump没指定用户名密码啥我运行候费用输入密码呢莫着急马揭晓答案mysql5.6(具体版本编号记)密码写脚本运行警告告诉要密码写脚本危险我伙伴该办呢官给解决案期望配置my.cnf文件所现打my.cnf加入字段:

两条运行脚本提示要输入密码马测试看否功没问题我进入步

第二步:何自备份oss始前我要做两件事

1、登录阿云控制台点右管理控制台点左产品与服务第二列点击象存储OSS没通要通通直接点击右新建bucket创建bucket记住buket名字(注:其实通api直接创建bucket *** 作所我用控制台创建降低理解难度)

2、始写传脚本要导入osssdk所要安装比较简单跟安装其python包没啥区别解压进入目录运行python setup.py install 安装完毕接看我何使用全部代码:

#!/usr/bin/python env

#autor:glacier

#date:2015-11-16

import os,os.path,time

import operator

import time

from oss.oss_api import *

prefix = '/home/dbback'

logtime = time.strftime(time.ctime())

#filelist = [ file for file in os.listdir(os.path.dirname(os.path.abspath(__file__))) if os.path.isfile(file) ]

filelist = [ file for file in os.listdir(prefix) if os.path.isfile(prefix + '/' + file) ]

def get_time(filename):

ft = os.stat(filename)

return ft.st_ctime

#def get_max():

# flist = []

# for file in filelist:

# flist.append(os.stat(file).st_ctime)

# return max(flist)

def get_dist():

d = {}

for file in filelist:

d[file] = get_time(prefix + '/' + file)

return d

if __name__ == '__main__':

#maxtime = get_max()

d = get_dist()

#dic= sorted(d.iteritems(), key=lambda d:d[1], reverse = True)

upfile = max(d.iteritems(), key=operator.itemgetter(1))[0]

endpoint = "your aliyun endpoint"

accessKeyId, accessKeySecret="your accessKeyId","your accessKeySecret "

oss = OssAPI(endpoint, accessKeyId, accessKeySecret)

res = oss.put_object_from_file("bucketname",upfile,prefix + '/' + upfile)

if res.status != 200:

with open('/var/log/dbback.log', 'a+') as f:

f.write(logtime + ' back failed' + '\n')

我接析脚本内容其脚本注释行都用看我编写程测试用始我设定备份文件目录记录志间备份目录所文件列表(列表其实式我用简单式文件列表慢)定义两函数get_time()函数获取文件创建间戳get_dist()函数获取文件名间戳字典主函数部比较难理解根据字典value排序获文件名d.iteritems()获字典每key,valuekey指定函数operator.itemgetter(1)表示用value排序(两元素key 0value1)间戳排序完返key[0]做工作脚本其部内容我说都见用没难于理解脚本介绍接进入我步

第三步:脚本写入crontab具体候执行根据家各自业务同设置没特别


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9891462.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-03
下一篇 2023-05-03

发表评论

登录后才能评论

评论列表(0条)

保存