我正在用Java开发一个系统,它读取所有MySQL数据库表,执行一些操作,最后将所有数据写入一个文件(每个表的单独文件)。
由于所有数据库表具有不同的列数和不同的行数,因此如果数据高于我们的系统可以处理,则可能存在内存问题。因此,我需要编写逐块读取表值的代码并将该数据写入文件中;经过一些迭代后,所有数据都写入该文件。
我相信这种方法可以在任何具有任何RAM大小的系统中运行,这样该系统就可以运行而不会遇到内存问题。目前,对于任何表,我限制查询结果并将结果写入一个文件,并反复迭代此过程,直到不处理所有结果。这里所有表的限制大小和迭代次数的值都是动态的,即取决于行数,列数和RAM大小。
以下是目前为止编写的代码。
public static void main(String[] args) throws Exception {
List<String> dbList = MySqlUtils.getAllTableNames("datahouse");
for (String tableName : dbList) {
processTable(tableName);
}
}
public static void processTable(String tableName) throws Exception {
String dbname = "datahouse";
int startIndex = 0;
int limit = getMySqlQueryLimit(dbname, tableName);
int endIndex = limit;
int iteratorLength = getIteratorLength(dbname, tableName);
for (int i = 1; i <= iteratorLength; i++) {
ResultSet resultSet = getResultSet(tableName, startIndex, endIndex);
while (resultSet.next()) {
// Write into file after some operation
}
startIndex = endIndex;
endIndex += limit;
}
}
public static ResultSet getResultSet(String tableName, int startLimit, int endLimit) throws SQLException {
StringBuilder builder = new StringBuilder();
builder.append("SELECT * FROM " + tableName);
builder.append("ORDER BY id ASC limit (");
builder.append(startLimit);
builder.append(",");
builder.append(endLimit);
builder.append(")");
return MySqlUtils.getStatement().executeQuery(builder.toString());
}
public static int getMySqlQueryLimit(String dbName, String tableName) throws SQLException {
long ramSize = SystemUtils.getPhysicalMemorySize();
int columnSize = getColumnCount(dbName, tableName);
int totalRows = getRowsCount(dbName, tableName);
//TODO
return 0;
}
public static int getIteratorLength(String dbName, String tableName) {
try {
long ramSize = SystemUtils.getPhysicalMemorySize();
int columnSize = getColumnCount(dbName, tableName);
int totalRows = getRowsCount(dbName, tableName);
//TODO
return 0;
} catch (SQLException e) {
e.printStackTrace();
return 0;
}
}
在processTable()
方法中,limit
和iteratorLength
之间存在依赖关系。是否有任何算法(或任何数学公式)可以计算getMySqlQueryLimit()
和getIteratorLength()
的值,以便此代码可以在任何独立于RAM大小的系统中执行,即不会遇到内存问题?