您的位置:首页 > 数据库 > MySQL

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

2015-02-27 10:52 267 查看
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 m
9c21
ain(String[] args) {
String tableName = "mobile_main_sum";
String date = "2014-09-17";
String selectSql = "SELECT * FROM " + tableName
+ " WHERE create_date=?";
exportInsert(tableName, selectSql, date);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐