我正试图将DB查询的ResultSet
保存到ArrayList
中,用作写入文件的输入,但内存不足。我正在读的表中大约有116k行数据。我尝试过在readDB()
方法中直接写入该文件,它创建了一个大约3.3 MB的CSV
文件。这是我的密码。
public class Main {
public static void main(String[] args) {
DBAccess dbAccess = new DBAccess();
}
}
读取数据库的类和方法。
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DBAccess {
public List<String> readDB() {
String url = "jdbc:Cobol://Dev/Project Files/DatAndCpyFiles";
try (Connection con = DriverManager.getConnection(url, "", "");
Statement stmt = con.createStatement())
{
stmt.setFetchSize(10);
Class.forName("com.hxtt.sql.cobol.CobolDriver").newInstance();
String sql = "select * from PROFS";
ResultSet rs = stmt.executeQuery(sql);
List<String> result = new ArrayList<>();
ResultSetMetaData resultSetMetaData = rs.getMetaData();
int iNumCols = resultSetMetaData.getColumnCount();
for (int i = 1; i <= iNumCols; i++) {
result.add(resultSetMetaData.getColumnLabel(i) + ";");
}
String row;
while (rs.next()) {
for (int i = 1; i <= iNumCols; i++) {
row = rs.getString(i);
row = row == null ? " " : row.replaceAll("u0086", "å");
row = row == null ? " " : row.replaceAll("u008F", "Å");
row = row == null ? " " : row.replaceAll("u0084", "ä");
row = row == null ? " " : row.replaceAll("u008E", "Ä");
row = row == null ? " " : row.replaceAll("u0094", "ö");
row = row == null ? " " : row.replaceAll("u0099", "Ö");
row = row == null ? " " : row.replaceAll("u0081", "ü");
row = row == null ? " " : row.replaceAll("u009A", "Ü");
row = row == null ? " " : row.replaceAll("u0082", "é");
row = row == null ? " " : row.replaceAll("u0090", "É");
result.add(result + row.trim() + ";");
}
}
rs.close();
System.out.println("Returning result");
return result;
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
return null;
}
}
}
错误消息
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3332)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:124)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:448)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at java.util.AbstractCollection.toString(AbstractCollection.java:462)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at se.spedweb.DBAccess.readDB(DBAccess.java:56)
at se.spedweb.Main.main(Main.java:15)
我还可以使用什么其他数据结构?我用错方法了吗?我可以只将append
写入一个文件,而不是在方法中列出add
,但我认为在单独的类中写入文件和读取数据库会更干净,也许这是错误的。
如果您使用命令行选项运行java,请尝试使用-Xmx,您可以手动设置堆的大小。尝试将其设置为-Xmx2048m。注意:如果你使用IDE,有一些方法可以做到,一个快速的谷歌会告诉你如何更改它