根据查询语句导出mysql到sql文件

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sjzs.db.BoneCPUtils;
import com.sjzs.web.Constants;

public class Export {
    private static final Logger logger = LoggerFactory.getLogger(Export.class);
    private static final String BASE_EXPORT_FILE_NAME = Constants.SETTINGS_PROPERTIES
            .get("base_export_filepath");
    private static final int SECTION_COUNT = 500;
    static {
        File file = new File(BASE_EXPORT_FILE_NAME);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static void exportInsert(String tableName, String sql,
            Object... params) {
        String fullFilename = BASE_EXPORT_FILE_NAME + "export_insert_"
                + tableName + ".sql";
        logger.info("write to:{}", fullFilename);
        File file = new File(fullFilename);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                logger.error("{}", e);
            }

        }
        OutputStream output = null;
        try {
            output = new FileOutputStream(file);
            IOUtils.write(getInsertSql(tableName, sql, params), output);
        } catch (IOException e) {
            logger.error("{}", e);
        } finally {
            IOUtils.closeQuietly(output);
        }
    }

    private static String getInsertSql(String tableName, String selectSql,
            Object... params) {
        Connection connection = null;
        PreparedStatement prepareStatement = null;
        ResultSet rs = null;
        StringBuilder insertSql = new StringBuilder();
        try {
            connection = BoneCPUtils.getInstance().getZSConnection();
            prepareStatement = connection.prepareStatement(selectSql);
            int i = 1;
            for (Object param : params) {
                prepareStatement.setObject(i++, param);
            }
            logger.info("selectSql:{}", selectSql);
            rs = prepareStatement.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            // 取得全部列数
            int colCount = rsmd.getColumnCount();
            String preSql = getInsertPreSql(tableName, colCount, rsmd);
            int count = 1;
            int rowCount = getRowCount(rs);
            boolean divideExactly = false; 
            while (rs.next()) {
                if(count == 1){
                    insertSql.append(preSql);
                }
                insertSql.append("(");
                for (i = 1; i <= colCount; i++) {
                    if (i != 1) {
                        insertSql.append(", ");
                    }
                    if (rsmd.isAutoIncrement(i)) {
                        insertSql.append("null");
                    } else {
                        insertSql.append("'").append(rs.getObject(i))
                                .append("'");
                    }
                }
                insertSql.append("),").append("\n");
                if(count % SECTION_COUNT == 0){
                    insertSql.deleteCharAt(insertSql.length() - 1);
                    insertSql.deleteCharAt(insertSql.length() - 1);
                    insertSql.append(";").append("\n");
                    if(count != rowCount){
                        insertSql.append(preSql);
                    } else {
                        divideExactly = true;
                    }
                }
                ++count;
            }
            if(!divideExactly){
                insertSql.deleteCharAt(insertSql.length() - 1);
                insertSql.deleteCharAt(insertSql.length() - 1);
                insertSql.append(";");
            }
        } catch (Exception e) {
            logger.error("{}", e);
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    logger.error("{}", e);
                }
            }
            if (prepareStatement != null) {
                try {
                    prepareStatement.close();
                } catch (SQLException e) {
                    logger.error("{}", e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    logger.error("{}", e);
                }
            }
        }
        return insertSql.toString();
    }

    private static int getRowCount(ResultSet rs) throws SQLException{
        int row = rs.getRow();
        rs.last();
        int rowCount = rs.getRow();
        rs.absolute(row);
        return rowCount;
    }
    private static String getInsertPreSql(String tableName, int colCount, ResultSetMetaData rsmd)
            throws SQLException {
        StringBuilder preSql = new StringBuilder("INSERT INTO ");
        preSql.append("`").append(tableName).append("`");
        preSql.append("(");
        for (int i = 1; i <= colCount; i++) {
            // 取得全部列名
            preSql.append("`").append(rsmd.getColumnName(i)).append("`,");
        }
        preSql.deleteCharAt(preSql.length() - 1);
        preSql.append(")");
        preSql.append(" VALUES ").append("\n");
        return preSql.toString();
    }

    public static void main(String[] args) {
        String tableName = "mobile_main_sum";
        String date = "2014-09-17";
        String selectSql = "SELECT * FROM " + tableName
                + " WHERE create_date=?";
        exportInsert(tableName, selectSql, date);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值