转载 javaweb sql备份和还原

	   
	@Action(value = "beifen")
	public void beifen() throws Exception, IOException, SQLException {
    	SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式  取月份 日期
		String riqi=df2.format(new Date());
		File dir = new File(this.imgFileStore.getRootFile().getPath()+ "/sqlbeifen/"+riqi);
    	if (!dir.exists()) {
			dir.mkdirs();
		}
    	String weburl=this.imgFileStore.getRootFile().getPath()+ "/sqlbeifen/"+riqi;
    	
    	String fileFileName="123.bak";
        
		String name = new Date().getTime()+ fileFileName.substring(fileFileName.lastIndexOf("."));// 生成随机文件名
        File file = new File(weburl);  
		String path = file.getPath() + "\\" + name;// name文件名  
		String bakSQL = "backup database hoosee_ydoa  to disk=? with init";// SQL语句  
		PreparedStatement bak = DataBaseUtil.getConnection().prepareStatement(bakSQL);  
		bak.setString(1, path);// path必须是绝对路径  
		bak.execute(); // 备份数据库  
		bak.close();  
		String data=imgFileStoreHttp.getRootFilePath()+ "/sqlbeifen/"+riqi+"/"+name;
		printWriter(data);
	}
	
	  
		/*
		 * 输出页面
		 */
		public void printWriter(String msgs) throws Exception, IOException {
			// 指定输出内容类型和编码
			ServletActionContext.getResponse().setContentType(
					"text/html;charset=utf-8");
			// 获取输出流,然后使用
			PrintWriter out = ServletActionContext.getResponse().getWriter();
			// 直接进行文本操作
			out.print(msgs);
			out.flush();
			out.close();
		}
		
package com.hoosee.actions.Family;

import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.SQLException;  
  
public class DataBaseUtil {  
    /** 
     * 获取数据库连接 
     * @return Connection 对象 
     */  
    public static Connection getConnection() {  
        Connection conn = null;  
        try {  
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  
            String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=hoosee_ydoa";  
            String username = "sa";  
            String password = "123";   
            conn = DriverManager.getConnection(url, username, password);  
              
        } catch (ClassNotFoundException e) {  
            e.printStackTrace();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
        return conn;  
    }  
      
    public static void closeConn(Connection conn) {  
        if (conn != null) {  
            try {  
                conn.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
}  

猜你喜欢

转载自my.oschina.net/u/2299924/blog/822845