mysql数据库备份oss_java mysql数据库的备份与还原

package com.db;

import java.sql.*;

import java.util.*;

/**

*

* @author zhaozhi3758

* @desc 底层数据库操作封装

*/

public class JdbcExcute {

/**

* 获取链接

* @return

*/

public Connection getCon(){

Connection conn = null;

try {

Class.forName("com.mysql.jdbc.Driver");// 加载驱动

String url = "jdbc:mysql://localhost:3306/libraryv1?useUnicode=true&characterEncoding=utf-8&useOldAliasMetadataBehavior=true";

conn = DriverManager.getConnection(url, "root", "123");// 建立连接

conn.setAutoCommit(false);

} catch (ClassNotFoundException e) {

e.printStackTrace();

}catch (SQLException e) {

e.printStackTrace();

}

return conn;

}

/**

* 得到查询结果集的字段结构

* @param rs

* @return 字段结果集

*/

/*public HashMap getDataColl(ResultSet rs){

HashMap mapcoll = new HashMap();

try {

ResultSetMetaData rsmd = rs.getMetaData();

for(int i=1;i<=rsmd.getColumnCount();i++){

String filedName=rsmd.getColumnName(i);

System.out.println("*******"+filedName);

//String fileType = rsmd.getColumnTypeName(i);

mapcoll.put(filedName, "");

}

} catch (Exception e) {

e.printStackTrace();

}

return mapcoll;

}*/

/**

* 获得查询数据,使用HashMap进行封装

* @param sqlstr 查询的SQL语句

* @return

*/

public ArrayList selQuery(String sqlstr){

Connection connetcion=null;

Statement stm=null;

try {

connetcion = getCon();

connetcion.setAutoCommit(true);

} catch (Exception e1) {

e1.printStackTrace();

}

ArrayList datalist = new ArrayList();

ResultSet rs = null;

if(sqlstr.equals(""))

return null;

try {

stm=connetcion.createStatement();

rs = stm.executeQuery(sqlstr);

ResultSetMetaData rsmd = rs.getMetaData();

int colum=rsmd.getColumnCount();

//HashMap map = getDataColl(rs);

//Object[] keys = map.keySet().toArray();

while(rs.next()){

HashMap dataSet = new HashMap();

for(int i=1;i<=colum;i++){

String strFieldName = rsmd.getColumnName(i).toLowerCase();

// if(keys[i].toString().equals("COLUMN_NAME"))keys[i]="Field";

// if(keys[i].toString().equals("COLUMN_TYPE"))keys[i]="Type";

// if(keys[i].toString().equals("IS_NULLABLE"))keys[i]="Null";

// if(keys[i].toString().equals("COLUMN_KEY"))keys[i]="Key";

// if(keys[i].toString().equals("COLUMN_DEFAULT"))keys[i]="Default";

// if(keys[i].toString().equals("EXTRA"))keys[i]="Extra";

dataSet.put(strFieldName, rs.getObject(i));

}

datalist.add(dataSet);

}

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

if(stm!=null)stm.close();

if(connetcion!=null)connetcion.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

return datalist;

}

/**

* 执行数据库增删改操作

* @param sqlstr 增删改的SQL语句

* @return 成功:0 失败:-1

*/

public int saveOrUpdate(String sqlstr){

Connection connetcion=null;

try {

connetcion = getCon();

connetcion.setAutoCommit(true);

} catch (Exception e1) {

e1.printStackTrace();

}

try {

connetcion.createStatement().execute(sqlstr);

return 0;

} catch (Exception e) {

e.printStackTrace();

return -1;

}finally{

try {

if(!connetcion.isClosed()){

connetcion.close();

}

} catch (SQLException e) {

e.printStackTrace();

}

}

}

public static void main(String[] args) {

JdbcExcute dbExcute=new JdbcExcute();

System.out.println(dbExcute.selQuery("SELECT * FROM reader"));

}

}

2.操作业务类

package com.db;

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.*;

public class DbOper {

private String tableName;

private String dbName="libraryv1";

private String _username = "root";

private String _password = "123";

private String _host = "localhost";

private String _port="3306";

public String getTableName() {

return tableName;

}

public void setTableName(String tableName) {

this.tableName = tableName;

}

public String getDbName() {

return dbName;

}

public void setDbName(String dbName) {

this.dbName = dbName;

}

public String get_username() {

return _username;

}

public void set_username(String _username) {

this._username = _username;

}

public String get_password() {

return _password;

}

public void set_password(String _password) {

this._password = _password;

}

public String get_host() {

return _host;

}

public void set_host(String _host) {

this._host = _host;

}

public String get_port() {

return _port;

}

public void set_port(String _port) {

this._port = _port;

}

/**

* 查询指定数据库的所有表名

* @param dbName 数据库名称

* @return ArrayList

*/

public ArrayList selAllTableInfo(String dbName){

//返回的结果集

ArrayList resultList = new ArrayList();

JdbcExcute exec = new JdbcExcute();

String sql = "select table_name, table_type,engine from information_schema.tables where table_schema='"+this.dbName+"' order by table_name asc";

resultList = exec.selQuery(sql);

return resultList;

}

/**

* 查询指定表的表结构

* @param tableName 表名

* @return ArrayList

*/

public ArrayList selTableStructure(String tableName){

ArrayList resultList = new ArrayList();

JdbcExcute exec = new JdbcExcute();

String sql = "desc "+tableName;

resultList = exec.selQuery(sql);

return resultList;

}

/**

* 根据路径生成备份数据库的Shell字符串

* @param targetName 要备份的对象名:只能为表名和数据库名称

* @return 实际执行的shell命令

*/

public String getBackupShellString(String targetName){

String basepath=Thread.currentThread().getContextClassLoader().getResource("").toString();

String backFile = "";

String database_tools_path=basepath.substring(6, basepath.length()-4)+"dbtools/";//备份工具路径

if(targetName.equals(this.dbName)){//若要备份整个数据库

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

backFile = "F:/database/"+targetName+"_"+sdf.format(new Date())+".sql";//要备份的文件

targetName = "";

}else{

backFile = "F:/tables/"+targetName+".sql";

}

String OSType = System.getProperty("os.name");

String shellStr = "";

if(OSType.indexOf("Windows")!=-1){

shellStr = database_tools_path+"mysqldumpwin.exe -h "+this._host+" -P"+this._port+" -u"+this._username+" -p"+

this._password+" --result-file="+backFile+" --default-character-set=gbk "+this.dbName+" "+targetName;

}else{

shellStr = database_tools_path+"mysqldump -h "+this._host+" -P"+this._port+" -u"+this._username+" -p"+

this._password+" --result-file="+backFile+" --default-character-set=gbk "+this.dbName+" "+targetName;

}

System.out.print("##############"+shellStr);

return shellStr;

}

/**

* 备份数据库

* @param targetName 要备份的对象名:只能为表名和数据库名称

* @return 成功:TRUE 失败:FALSE

* 备份表直接备份在指定文件夹,备份库则按日期备份到指定的文件夹

*

*/

public boolean backup(String targetName){

String backFilePath = "";

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

String backDirString = "F:/database/";//默认备份库

try {

if(!targetName.equals(this.dbName)){//备份表

File tableDir = new File("F:/tables/");

if(!tableDir.exists()){//存放表的文件夹不存在

tableDir.mkdir();

System.out.println("--------->"+tableDir);

}

backFilePath ="F:/tables/"+targetName+".sql";//要备份的文件

}else {//备份库

backFilePath ="F:/database/"+targetName+"_"+sdf.format(new Date())+".sql";//要备份的文件

File backDir = new File(backDirString);

if(!backDir.exists()){//存放库的文件夹不存在

backDir.mkdir();

}

}

//判断要备份的文件是否已存在

File backFile = new File(backFilePath);

if(backFile.exists()){

backFile.delete();

}

Runtime runt = Runtime.getRuntime();

//Process proc = runt.exec("D:/myec6_tomcat/webapps/cms/dbtools/mysqldumpwin.exe -h 127.0.0.1 -P3306 -uroot -p123 --result-file=F:/tables/menuinfo.sql --default-character-set=gbk bizoss_cms menuinfo");

Process proc = runt.exec(getBackupShellString(targetName));

int tag = proc.waitFor();//等待进程终止

if(tag==0){

return true;

}else{

return false;

}

} catch (Exception e) {

e.printStackTrace();

return false;

}

}

/**

* 恢复数据库

* @param targetName 要备份的对象名:只能为表名和数据库名称

* @return 成功:TRUE 失败:FALSE

*/

public boolean restore(String targetName){

try {

Runtime runt = Runtime.getRuntime();

Process proc;

String cmdtext = this.getRestoreShellString(targetName);

if(System.getProperty("os.name").indexOf("Windows")!=-1){

String[] cmd= { "cmd", "/c", cmdtext};

proc= runt.exec(cmd);

}else{

String[] cmd= { "sh","-c",cmdtext};

proc = runt.exec(cmd);

}

System.out.println(cmdtext);

int tag = proc.waitFor();//等待进程终止

System.out.println("进程返回值为tag:"+tag);

if(tag==0){

return true;

}else{

return false;

}

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

/**

* 根据路径生成恢复数据库的Shell字符串

* @param targetName targetName 要还原的对象名:只能为表名和数据库名称

* @return 恢复数据时实际执行的shell

*/

public String getRestoreShellString(String targetName){

String basepath=Thread.currentThread().getContextClassLoader().getResource("").toString();

String database_tools_path=basepath.substring(6, basepath.length()-4)+"dbtools/";//备份工具路径

String backFile = "";//已备份的文件

if(targetName.indexOf(this.dbName) == -1){//还原表

backFile = "f:/tables/"+targetName+".sql";

}else{//还原库

backFile ="f:/database/"+targetName;

}

String OSType = System.getProperty("os.name");

String shellStr = "";

if(OSType.indexOf("Windows")!=-1){

shellStr = database_tools_path+"mysqlwin.exe -h "+this._host+" -P"+this._port+" -u"+this._username+" -p"+

this._password+" --default-character-set=gbk "+this.dbName +" < "+backFile;

}else{

shellStr = database_tools_path+"mysql -h "+this._host+" -P"+this._port+" -u"+this._username+" -p"+

this._password+" --default-character-set=gbk "+this.dbName+" < "+backFile;

}

return shellStr;

}

public static void main(String[] args) {

DbOper db=new DbOper();

// System.out.println(db.selAllTableInfo("libraryv1"));

System.out.println(db.selTableStructure("bookinfo"));

//System.out.println(db.backup("t"));

// System.out.println(System.getProperty("os.name"));

//System.out.println(db.restore("t"));

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2010-01-31 16:21

浏览 5765

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一些可能用到的代码片段: 1. 从OSS获取Excel文件: ```java // 初始化OSS客户端 OSSClient ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 获取Excel文件流 OSSObject ossObject = ossClient.getObject(bucketName, objectName); InputStream inputStream = ossObject.getObjectContent(); ``` 2. 解析Excel文件: ```java // 创建工作簿 Workbook workbook = WorkbookFactory.create(inputStream); // 获取第一个工作表 Sheet sheet = workbook.getSheetAt(0); // 遍历工作表中的每一行 for (Row row : sheet) { // 获取每一行中的每一个单元格 for (Cell cell : row) { // 处理单元格的数据 String value = cell.getStringCellValue(); // ... } } ``` 3. 连接MySQL数据库: ```java // 加载MySQL驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 建立数据库连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password"); ``` 4. 将数据插入MySQL数据库: ```java // 创建PreparedStatement对象 PreparedStatement pstmt = conn.prepareStatement("INSERT INTO mytable (column1, column2, ...) VALUES (?, ?, ...)"); // 设置参数 pstmt.setString(1, value1); pstmt.setInt(2, value2); // ... // 执行SQL语句 pstmt.executeUpdate(); ``` 通过组合以上代码片段,您应该能够完成从OSS存储的Excel文件中读取数据并将其导入MySQL数据库的任务。请注意,此代码仅提供了一些基本的代码片段,实际应用中可能需要进行更多的空值检查、异常处理等操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值