代码如下,做一个数据脚本的备份与还原,从数据库查询所有记录,拼接成插入语句,数据库中有600多万条数据,在自的电脑上试,写到txt文件中足足花了半个小时的时间啊。。。。。不知道哪里有问题,麻烦各位指点一下
[code="java"]
/**
* 如果记录大于10000行,则 分页抓取,每次抓取10000条,这里只适应于在mysql
* @param rowCount
* 总记录数
* @param table
* 表名
* @param writer
* 输入流
*/
private static BufferedWriter fetchByPage(int rowCount, String table,
BufferedWriter writer) {
final int fetchSize = 10000;
final int pageSize = rowCount % fetchSize == 0 ? rowCount / fetchSize
: rowCount / fetchSize + 1;
int currentPage = 1;
Connection conn = null;
Statement stsm = null;
ResultSet rs = null;
try {
conn = newConnection();
conn.setAutoCommit(false);
stsm = conn.createStatement();
if (isSqlServer(conn)) {
writer
.write("SET IDENTITY_INSERT [dbo].[" + table
+ "] ON; \n");
} else {
writer.write("SET FOREIGN_KEY_CHECKS=0;\n"); // 默认是mysql
}
while (currentPage <= pageSize) {
String sql = "select * from " + table + " limit "
+ (currentPage - 1) * fetchSize + "," + fetchSize;
rs = stsm.executeQuery(sql);
writeByRow(conn, table, rs, writer);
currentPage++;
}
if (isSqlServer(conn)) {
writer.write("SET IDENTITY_INSERT [dbo].[" + table
+ "] OFF; \n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
if (!conn.isClosed())
conn.close();
if (stsm != null)
stsm.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return writer;
}
private static BufferedWriter writeByRow(Connection conn, String tableName,
ResultSet rs, BufferedWriter writer) throws Exception {
while (rs.next()) {
StringBuilder insertSql = new StringBuilder();
insertSql.append("insert into ");
String[] columnNames = getColumnNames(rs);
if (isSqlServer(conn)) {
insertSql.append("" + tableName + ";
for (String columnName : columnNames) {
insertSql.append("[" + columnName + "],");
}
} else {
insertSql.append("" + tableName + "
(");
for (String columnName : columnNames) {
insertSql.append("" + columnName + "
,");
}
}
insertSql.deleteCharAt(insertSql.length() - 1);
insertSql.append(")");
insertSql.append(" values(");
for (int i = 0; i < columnNames.length; i++) {
String columnClassName = rs.getMetaData().getColumnClassName(
i + 1);
if (rs.getObject(i + 1) != null) {
if (columnClassName.equalsIgnoreCase("java.lang.String")) {
String strValue = rs.getString(columnNames[i]);
strValue = strValue.replaceAll("\r", "\\\\r");
strValue = strValue.replaceAll("\n", "\\\\n");
insertSql.append("'" + strValue + "',");
} else {
insertSql.append("'" + rs.getObject(i + 1) + "',");
}
} else {
insertSql.append(rs.getObject(i + 1) + ",");
}
}
int index = insertSql.toString().lastIndexOf(",");
String sqlText = insertSql.toString().substring(0, index) + ")";
writer.write(sqlText + ";\n");
}
return writer;
}
[/code]