200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > java生成mysql数据库建表语句 字段 字段类型 字段注释 可实现不用mysqldump备份数据库

java生成mysql数据库建表语句 字段 字段类型 字段注释 可实现不用mysqldump备份数据库

时间:2022-04-14 00:09:57

相关推荐

java生成mysql数据库建表语句 字段 字段类型 字段注释 可实现不用mysqldump备份数据库

使用 mysqldump 备份数据库也是可行的,因为每次备份的时候都需要mysqldump这个文件, 我在windows备份时没问题,但是放到linux上面时,centos系统死活不认这个文件,但又不想装mysql,一气之下自己研究了个不需要mysqldump就可以备份的程序,

如果看了以下代码还有不懂的地方,这个网站有我的联系方式, 站长就是我本人

废话不多说,直接上代码

添加jdbc驱动 和httpClient的 maven依赖

<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient-cache</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.1.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.15</version><scope>runtime</scope></dependency>

备份程序

package com.mysql.bak;import java.math.BigDecimal;import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;import com.utils.FileUtils;/*** 利用jdbc备份mysql数据库--不用mysqldump**/public class BakDateBase {private String DRIVER = "com.mysql.jdbc.Driver";private String URL = null; // "jdbc:mysql://182.xxx.xxx.xxx:3306/xd_love_dev?useUnicode=true&characterEncoding=utf8";private String USERNAME = null;// "root";private String PASSWORD = null;//"woaini";// 备份的文件地址private String filePath;private Connection conn = null;private String SQL = "SELECT * FROM ";// 数据库操作/*** * <构造函数>* * @param ip* 数据库ip地址* @param database* 数据库名称* @param userName* 数据库用户名* @param password* 密码* @param bakFilePath* 备份的地址*/public BakDateBase(String ip, String database, String userName, String password, String bakFilePath) {try {Class.forName(this.DRIVER);this.URL = String.format("jdbc:mysql://%s:3306/%s?useUnicode=true&characterEncoding=utf8", ip, database);this.USERNAME = userName;this.PASSWORD = password;SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-ddHH时mm分ss秒");String datetime = tempDate.format(new java.util.Date());//自动加上时间戳datetime = datetime + "_数据库名称:" + database ;if(bakFilePath.indexOf(".") != -1) {bakFilePath = bakFilePath.replace(".", datetime+".");} else {bakFilePath = datetime + ".sql";}this.filePath = bakFilePath;} catch (ClassNotFoundException e) {e.printStackTrace();System.err.println("can not load jdbc driver");}}/*** 获取数据库连接** @return*/private Connection getConnection() {try {if (null == conn) {conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);}} catch (SQLException e) {e.printStackTrace();System.err.println("get connection failure");}return conn;}/*** 关闭数据库连接* * @param conn*/private void closeConnection(Connection conn) {if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();System.err.println("close connection failure");}}}/*** 获取数据库下的所有表名*/private List<String> getTableNames() {List<String> tableNames = new ArrayList<String>();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<String> getColumnNames(String tableName) {List<String> columnNames = new ArrayList<String>();// 与数据库的连接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<String> getColumnTypes(String tableName) {List<String> columnTypes = new ArrayList<String>();// 与数据库的连接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;}/*** * <p>* 生成建表语句* </p>* * @param tableName* @return* @author 叶新东(18126064335) 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<String> getColumnComments(String tableName) {// 与数据库的连接Connection conn = getConnection();PreparedStatement pStemt = null;String tableSql = SQL + tableName;List<String> columnComments = new ArrayList<String>();// 列名注释集合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;}/*** * <p>* 备份表数据* </p>* * @param tableName* @return* @author () 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<String> columnTypes = getColumnTypes(tableName);// 获取所有 字段List<String> 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", "<br/>");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;}/*** * <p>* 获取表数据一行的所有值* </p>* * @param rs* @param size* @author 9月6日 上午11:03:05*/private String getRowValues(ResultSet rs, int size, List<String> 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;}}/*** * <p>* 根据类型获取字段值* </p>* * @param obj* @return* @author 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 格式 YYYYString 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-DDreturn resultSet.getString(index);} else if ("time".equals(columnType) || "TIME".equals(columnType)) {// 时间类型:范围 '-838:59:59'到'838:59:59' 格式 HH:MM:SSreturn 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:SSreturn 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 9月6日 下午3:30:43*/public void startBak() {try {List<String> 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.mon.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 {/*** * <p>* 创建文件* </p>* * @param path* @param fileName* @return* @author 叶新东(18126064335) -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) 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;}}/*** * <p>* 追加形式向文件写入内容* </p>* * @param filePath* @param content* @return* @author 叶新东(18126064335) -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) 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 转 outputStreamint 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 的文件,内容如下:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。