使用 mysqldump 备份数据库也是可行的,因为每次备份的时候都需要mysqldump这个文件, 我在windows备份时没问题,但是放到linux上面时,centos系统死活不认这个文件,但又不想装mysql,一气之下自己研究了个不需要mysqldump就可以备份的程序,
如果看了以下代码还有不懂的地方,这个网站有我的联系方式http://www.chn520.cn, 站长就是我本人

废话不多说,直接上代码
添加jdbc驱动 和httpClient的 maven依赖
org.apache.httpcomponents
httpclient
4.1.2
org.apache.httpcomponents
httpclient-cache
4.1.2
org.apache.httpcomponents
httpmime
4.1.2
/dependency>
br />
br />
dependency>
mysql
mysql-connector-java
/artifactId>
br />
version>5.1.15
/version>
br />
scope>runtime
/scope>
br />
br />
*
br />
* @param ip
br />
* 数据库ip地址
br />
* @param database
br />
* 数据库名称
br />
* @param userName
br />
* 数据库用户名
br />
* @param password
br />
* 密码
br />
* @param bakFilePath
br />
* 备份的地址
br />
*/
br />
public BakDateBase(String ip, String database, String userName, String password, String bakFilePath) {
br />
try {
br />
Class.forName(this.DRIVER);
br />
this.URL = String.format("jdbc:mysql://%s:3306/%s?useUnicode=true&characterEncoding=utf8", ip, database);
br />
this.USERNAME = userName;
br />
this.PASSWORD = password;
br />
SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-ddHH时mm分ss秒");
br />
String datetime = tempDate.format(new java.util.Date());
br />
//自动加上时间戳
br />
datetime = datetime + "_数据库名称:" + database ;
br />
if(bakFilePath.indexOf(".") != -1) {
br />
bakFilePath = bakFilePath.replace(".", datetime+".");
br />
} else {
br />
bakFilePath = datetime + ".sql";
br />
}
br />
this.filePath = bakFilePath;
br />
} catch (ClassNotFoundException e) {
br />
e.printStackTrace();
br />
System.err.println("can not load jdbc driver");
br />
}
br />
}
br />
/**
br />
* 获取数据库连接
br />
*
br />
* @return
br />
*/
br />
private Connection getConnection() {
br />
try {
br />
if (null == conn) {
br />
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
br />
}
br />
} catch (SQLException e) {
br />
e.printStackTrace();
br />
System.err.println("get connection failure");
br />
}
br />
return conn;
br />
}
br />
/**
br />
* 关闭数据库连接
br />
*
br />
* @param conn
br />
*/
br />
private void closeConnection(Connection conn) {
br />
if (conn != null) {
br />
try {
br />
conn.close();
br />
} catch (SQLException e) {
br />
e.printStackTrace();
br />
System.err.println("close connection failure");
br />
}
br />
}
br />
}
br />
/**
br />
* 获取数据库下的所有表名
br />
*/
br />
private List
String>getTableNames() {
List
tableNames = new ArrayList();
Connection conn = getConnection();
ResultSet rs = null;
try {
// 获取数据库的元数据
DatabaseMetaData db = conn.getMetaData();
// 从元数据中获取到所有的表名
rs = db.getTables(null, null, null, new String[] { "TABLE" });
while (rs.next()) {
tableNames.add(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
System.err.println("getTableNames failure");
} finally {
try {
if (null != rs) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
System.err.println("close ResultSet failure");
}
}
return tableNames;
}
/**
* 获取表中所有字段名称
*
* @param tableName
* 表名
* @return
*/
private List getColumnNames(String tableName) {
List columnNames = new ArrayList();
// 与数据库的连接
Connection conn = getConnection();
PreparedStatement pStemt = null;
String tableSql = SQL + tableName;
try {
pStemt = conn.prepareStatement(tableSql);
// 结果集元数据
ResultSetMetaData rsmd = pStemt.getMetaData();
// 表列数
int size = rsmd.getColumnCount();
for (int i = 0; i < size; i++) {
columnNames.add(rsmd.getColumnName(i + 1));
}
} catch (SQLException e) {
System.err.println("getColumnNames failure");
e.printStackTrace();
} finally {
if (pStemt != null) {
try {
pStemt.close();
} catch (SQLException e) {
e.printStackTrace();
System.err.println("getColumnNames close pstem and connection failure");
}
}
}
return columnNames;
}
/**
* 获取表中所有字段类型
*
* @param tableName
* @return
*/
private List getColumnTypes(String tableName) {
List columnTypes = new ArrayList();
// 与数据库的连接
Connection conn = getConnection();
PreparedStatement pStemt = null;
String tableSql = SQL + tableName;
try {
pStemt = conn.prepareStatement(tableSql);
// 结果集元数据
ResultSetMetaData rsmd = pStemt.getMetaData();
// 表列数
int size = rsmd.getColumnCount();
for (int i = 0; i < size; i++) {
columnTypes.add(rsmd.getColumnTypeName(i + 1));
}
} catch (SQLException e) {
e.printStackTrace();
System.err.println("getColumnTypes failure");
} finally {
if (pStemt != null) {
try {
pStemt.close();
} catch (SQLException e) {
e.printStackTrace();
System.err.println("getColumnTypes close pstem and connection failure");
}
}
}
return columnTypes;
}
/**
*
*
* 生成建表语句
*
*
* @param tableName
* @return
* @author 叶新东(18126064335) 2018年9月6日 上午9:35:49
*/
private String generateCreateTableSql(String tableName) {
String sql = String.format("SHOW CREATE TABLE %s", tableName);
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
pstmt = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
// 返回建表语句语句,查询结果的第二列是建表语句,第一列是表名
return rs.getString(2);
}
} catch (Exception e) {
e.printStackTrace();
try {
if (null != pstmt) {
pstmt.close();
}
} catch (Exception e2) {
e.printStackTrace();
System.err.println("关闭流异常");
}
}
return null;
}
/**
* 获取表中字段的所有注释
*
* @param tableName
* @return
*/
private List getColumnComments(String tableName) {
// 与数据库的连接
Connection conn = getConnection();
PreparedStatement pStemt = null;
String tableSql = SQL + tableName;
List columnComments = new ArrayList();// 列名注释集合
ResultSet rs = null;
try {
pStemt = conn.prepareStatement(tableSql);
rs = pStemt.executeQuery("show full columns from " + tableName);
while (rs.next()) {
columnComments.add(rs.getString("Comment"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
System.err.println("getColumnComments close ResultSet and connection failure");
}
}
}
return columnComments;
}
/**
*
*
* 备份表数据
*
*
* @param tableName
* @return
* @author () 2018年9月6日 上午10:18:07
*/
private String bakTableData(String tableName) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 备份建表语句
String createTableSql = generateCreateTableSql(tableName);
createTableSql = String.format(
"\n\n\n/**\n * table name :<%s>\n *\n */\n%s\n",
tableName, createTableSql);
FileUtils.writeFileContent(filePath, createTableSql);
// 获取字段类型
List columnTypes = getColumnTypes(tableName);
// 获取所有 字段
List columnNames = getColumnNames(tableName);
String columnArrayStr = null;
for (String column : columnNames) {
if (null == columnArrayStr) {
columnArrayStr = "`" + column + "`";
} else {
columnArrayStr = columnArrayStr + "," + "`" + column + "`";
}
}
String sql = String.format("select %s from %s", columnArrayStr, tableName);
conn = getConnection();
pstmt = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String rowValues = getRowValues(rs, columnNames.size(), columnTypes);
// 返回建表语句语句,查询结果的第二列是建表语句,第一列是表名
String insertSql = String.format("insert into %s (%s) values(%s);", tableName, columnArrayStr,
rowValues);
System.out.println(insertSql);
insertSql = insertSql.replaceAll("\n", "
");
insertSql = insertSql + "\n";
FileUtils.writeFileContent(filePath, insertSql);
}
} catch (Exception e) {
e.printStackTrace();
try {
if (null != pstmt) {
pstmt.close();
}
} catch (Exception e2) {
e.printStackTrace();
System.err.println("关闭流异常");
}
}
return null;
}
/**
*
*
* 获取表数据一行的所有值
*
*
* @param rs
* @param size
* @author 2018年9月6日 上午11:03:05
*/
private String getRowValues(ResultSet rs, int size, List columnTypeList) {
try {
String rowValues = null;
for (int i = 1; i <= size; i++) {
String columnValue = null;
// 获取字段值
columnValue = getValue(rs, i, columnTypeList.get(i - 1));
// 如果是空值不添加单引号
if (null != columnValue) {
columnValue = "'" + columnValue + "'";
}
// 拼接字段值
if (null == rowValues) {
rowValues = columnValue;
} else {
rowValues = rowValues + "," + columnValue;
}
}
return rowValues;
} catch (Exception e) {
e.printStackTrace();
System.out.println("获取表数据一行的所有值异常");
return null;
}
}
/**
*
*
* 根据类型获取字段值
*
*
* @param obj
* @return
* @author 2018年9月6日 上午11:16:00
*/
private String getValue(ResultSet resultSet, Integer index, String columnType) {
try {
if ("int".equals(columnType) || "INT".equals(columnType)) {
// 整数
Object intValue = resultSet.getObject(index);
if (null == intValue) {
return null;
}
return intValue + "";
} else if ("bigint".equals(columnType) || "BIGINT".equals(columnType)) {
// 长整形
Object value = resultSet.getObject(index);
if (null == value) {
return null;
}
return value + "";
} else if ("smallint".equals(columnType) || "SMALLINT".equals(columnType)) {
// 整数
Object value = resultSet.getObject(index);
if (null == value) {
return null;
}
return value + "";
} else if ("tinyint".equals(columnType) || "TINYINT".equals(columnType)) {
// 整数
Object value = resultSet.getObject(index);
if (null == value) {
return null;
}
return value + "";
} else if ("mediumint".equals(columnType) || "MEDIUMINT".equals(columnType)) {
// 长整形
Object value = resultSet.getObject(index);
if (null == value) {
return null;
}
return value + "";
} else if ("integer".equals(columnType) || "INTEGER".equals(columnType)) {
// 整数
Object value = resultSet.getObject(index);
if (null == value) {
return null;
}
return value + "";
} else if ("float".equals(columnType) || "FLOAT".equals(columnType)) {
// 浮点数
Object value = resultSet.getObject(index);
if (null == value) {
return null;
}
return value + "";
} else if ("double".equals(columnType) || "DOUBLE".equals(columnType)) {
// 浮点数
Object value = resultSet.getObject(index);
if (null == value) {
return null;
}
return value + "";
} else if ("decimal".equals(columnType) || "DECIMAL".equals(columnType)) {
// 浮点数-金额类型
BigDecimal value = resultSet.getBigDecimal(index);
if (null == value) {
return null;
}
return value.toString();
} else if ("char".equals(columnType) || "CHAR".equals(columnType)) {
// 字符串类型
String value = resultSet.getString(index);
return value;
} else if ("varchar".equals(columnType) || "VARCHAR".equals(columnType)) {
// 字符串类型
String value = resultSet.getString(index);
return value;
} else if ("tinytext".equals(columnType) || "TINYTEXT".equals(columnType)) {
// 字符串类型
String value = resultSet.getString(index);
return value;
} else if ("text".equals(columnType) || "TEXT".equals(columnType)) {
// 字符串类型
String value = resultSet.getString(index);
return value;
} else if ("mediumtext".equals(columnType) || "MEDIUMTEXT".equals(columnType)) {
// 字符串类型
String value = resultSet.getString(index);
return value;
} else if ("longtext".equals(columnType) || "LONGTEXT".equals(columnType)) {
// 字符串类型
String value = resultSet.getString(index);
return value;
} else if ("year".equals(columnType) || "YEAR".equals(columnType)) {
// 时间类型:范围 1901/2155 格式 YYYY
String year = resultSet.getString(index);
if (null == year) {
return null;
}
// 只需要年的字符即可,
return year.substring(0, 4);
} else if ("date".equals(columnType) || "DATE".equals(columnType)) {
// 时间类型:范围 '1000-01-01'--'9999-12-31' 格式 YYYY-MM-DD
return resultSet.getString(index);
} else if ("time".equals(columnType) || "TIME".equals(columnType)) {
// 时间类型:范围 '-838:59:59'到'838:59:59' 格式 HH:MM:SS
return resultSet.getString(index);
} else if ("datetime".equals(columnType) || "DATETIME".equals(columnType)) {
// 时间类型:范围 '1000-01-01 00:00:00'--'9999-12-31 23:59:59' 格式 YYYY-MM-DD HH:MM:SS
return resultSet.getString(index);
} else if ("timestamp".equals(columnType) || "TIMESTAMP".equals(columnType)) {
// 时间类型:范围 1970-01-01 00:00:00/2037 年某时 格式 YYYYMMDD HHMMSS 混合日期和时间值,时间戳
return resultSet.getString(index);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("获取数据库类型值异常");
return null;
}
}
/**
*
* <开始备份>
*
* @author 2018年9月6日 下午3:30:43
*/
public void startBak() {
try {
List tableNames = getTableNames();
System.out.println("tableNames:" + tableNames);
for (String tableName : tableNames) {
bakTableData(tableName);
// System.out.println(generateCreateTableSql(tableName));
// System.out.println("ColumnNames:" + getColumnNames(tableName));
// System.out.println("ColumnTypes:" + getColumnTypes(tableName));
// System.out.println("ColumnComments:" + getColumnComments(tableName));
}
// 统一关闭连接
closeConnection(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new BakDateBase("182.xxx.xxx.xxx", "xd_love_dev", "root", "woaini", "f:\\bak.sql").startBak();
}
} FileUtils.java
package com.xd.core.common.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.hibernate.validator.internal.util.logging.Log;
public class FileUtils {
/**
*
*
* 创建文件
*
*
* @param path
* @param fileName
* @return
* @author 叶新东(18126064335) 2018-6-21 上午11:50:26
* @throws Exception
*/
public static File createFile(String path, String fileName) throws Exception {
try {
// 目录
File file = new File(path);
// 判断文件夹/文件 是否存在
if (!file.exists()) {
// 创建目录
file.mkdirs();
}
// 文件
String filePath = path + fileName;
Date now = new Date();
SimpleDateFormat f = new SimpleDateFormat("今天是" + "yyyy年MM月dd日 E kk点mm分ss秒");
String suffix = f.format(now);
file = new File(filePath + suffix + ".txt");
// 判断文件夹/文件 是否存在
if (!file.exists()) {
// 如果不存在
// 创建文件
file.createNewFile();
} else {
// 如果已存在,创建一个新的文件
file = new File(filePath);
file.createNewFile();
}
return file;
} catch (Exception e) {
System.err.println("创建文件异常");
throw e;
}
}
/**
*
* <创建文件>
* @param
* @param
* @return
* @throws Exception
* @author 叶新东(18126064335) 2018年9月8日 下午1:27:16
*/
public static File createFileFolder(String filePath) throws Exception {
try {
// 目录
File file = new File(filePath);
// 判断文件夹/文件 是否存在
if (file.exists()) {
return file;
}
File parentFile = file.getParentFile();
//判断文件夹是否存在
if(!parentFile.exists()) {
//如果不存在创建目录
parentFile.mkdirs();
}
//创建文件
file.createNewFile();
return file;
} catch (Exception e) {
System.err.println("创建文件异常");
throw e;
}
}
/**
*
*
* 追加形式向文件写入内容
*
*
* @param filePath
* @param content
* @return
* @author 叶新东(18126064335) 2018-6-21 上午11:59:04
* @throws Exception
*/
public static void writeFileContent(String filePath, String content) throws Exception {
FileOutputStream fileOutStream = null;
PrintWriter printWriter = null;
try {
// true 表示以追加的形式写入内容
fileOutStream = new FileOutputStream(filePath, true);
printWriter = new PrintWriter(fileOutStream);
printWriter.write(content.toCharArray());
printWriter.flush();
} catch (Exception e) {
e.printStackTrace();
System.err.println("向文件写入内容异常");
throw e;
} finally {
try {
if (null != fileOutStream) {
fileOutStream.close();
}
if (null != printWriter) {
printWriter.close();
}
} catch (Exception e2) {
System.out.println("文件流关闭失败");
}
}
}
/**
*
* <写入文件>
*
* @param filePath
* @param input
* @throws Exception
* @author 叶新东(18126064335) 2018年9月7日 下午5:56:21
*/
public static void writeFile(String filePath, InputStream input) throws Exception {
OutputStream outputStream = null;
try {
//先创建文件
File file = createFileFolder(filePath);
outputStream = new FileOutputStream(file);
//inputStream 转 outputStream
int bytesWritten = 0;
int byteCount = 0;
byte[] bytes = new byte[1024];
while ((byteCount = input.read(bytes)) != -1) {
outputStream.write(bytes, bytesWritten, byteCount);
bytesWritten += byteCount;
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
//关闭流
if (null != input) {
input.close();
}
if (null != outputStream) {
outputStream.close();
}
}
}
}执行 main 方法后会在磁盘指定位置生成 .sql 的文件,内容如下:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/114460.html