Java 快速向Oracle数据库插入多行
我需要非常快地将许多sql行插入到oracle数据库中。IndexData是包含要插入oracle数据库的save方法的类Java 快速向Oracle数据库插入多行,java,sql,oracle,jdbc,Java,Sql,Oracle,Jdbc,我需要非常快地将许多sql行插入到oracle数据库中。IndexData是包含要插入oracle数据库的save方法的类 while ((line = in.readLine()) != null) { if(line.contains("numDocs")) { numDocs = in.readLine().trim(); //For Inserting IndexData id = new IndexData(timeStamp, 1, 2, numcDocs)
while ((line = in.readLine()) != null) {
if(line.contains("numDocs")) {
numDocs = in.readLine().trim();
//For Inserting
IndexData id = new IndexData(timeStamp, 1, 2, numcDocs);
id.save();
} else if(line.contains("indexSize")) {
indexSize = in.readLine().trim();
//For Inserting
IndexData id = new IndexData(timeStamp, 1, 3, indexSize);
id.save();
} else if(line.contains("indexReplicatedAt")) {
replicationTime = in.readLine().trim();
//For Inserting
IndexData id = new IndexData(timeStamp, 1, 4, replicationTime );
id.save();
}
}
BufferedReader inUrl = new BufferedReader (new InputStreamReader (isUrl));
String lineUrl;
Pattern regex = Pattern.compile("<str name=\"status\">(.*?)</str>");
while ((lineUrl = inUrl.readLine()) != null) {
if(lineUrl.contains("str name=\"status\"")) {
Matcher regexMatcher = regex.matcher(lineUrl);
if (regexMatcher.find()) {
status = regexMatcher.group(1);
//For Inserting
IndexData id = new IndexData(timeStamp, 1, 5, status);
id.save();
}
}
}
这是将多个sql语句插入oracle数据库的最佳方法。因为我一次又一次地打开IndexData类,为每个信息只在DB中插入一行。有没有比这更快的方法。如果您有任何建议,我们将不胜感激。请查看和-您可以创建一条准备好的语句,添加多组参数以进行执行,然后执行批处理。不过,您可能希望每批选择一定数量的插入,以限制内存中累积的“挂起”工作量。我感觉您的设计中有一股难闻的味道,比如您的实体对象负责创建和关闭prepare语句,数据库连接是“全局”的等等 有一些常见的方法可供您研究:
(而且,如果您发布代码,请确保正确缩进。现在简直是一团糟)这永远不会很好地扩展,但它取决于需要加载多少记录。通常,更好的选择是使用sql loader的直接路径加载,并可能并行加载。可以做的一件事是将查询写入文件,然后在单独的线程中将文件加载到DB中。
这是因为您所有的要求都只是插入查询。这有一个小问题,尽管如果文件加载失败,那么您不知道哪里出了问题。我想,这样可以减少内存占用,加快工作速度 谢谢你提供的信息。你能根据我的代码举个例子吗。根据您的建议,我必须修改IndexData类中的save方法。是吗?@RaihanJamal:您需要更改代码,将
保存
方法移出索引数据
,或者在索引数据
中使用静态方法保存列表
或类似内容。该方法将准备语句,然后循环要添加的项,设置参数并多次调用addBatch
,然后调用executeBatch
——可能在循环中执行所有这些操作以限制批的大小。@Jon Skeet您需要每xxxx条记录(1000条或更多)执行/清除批为了最大限度地减少内存使用。@SergeyGazaryan:是的,因此我的最后一句话:)+1 Oracle提供了几种将信息从文件加载到数据库的方法:SQL Loader和外部表是常用的方法。使用提供的功能的面向批量的方法总是比手工滚动的RBAR实现更快,不管调整得多么好?印度红?几千?数以百万计的?
public IndexData(String timestamp, String serveId, String informationId, String value ) {
this.timestamp=timestamp;
this.serverId=serverId;
this.informationId=informationId;
this.value=value;
}
//For Inserting
public void save() throws SQLException {
ps = DataSource.conn.prepareStatement (
"INSERT INTO table(timestamp, serverId, informationId, value) VALUES(?,?,?,?)");
ps.setString (1, timestamp);
ps.setString (2, serverId);
ps.setString (3, informationId);
ps.setString (4, value);
ps.executeUpdate();
ps.close ();
}