【发布时间】:2020-03-27 03:20:36
【问题描述】:
我正在为一个类项目的 java http 服务器编写后端,我必须使用 jdbc 将一些记录插入到数据库中。我一次插入的最大数量目前是 122,执行时间高达 18.7 秒,大约每秒 6.5 次插入。这非常慢,因为服务器需要能够在不到 5 秒的时间内响应插入记录的请求,而真正的服务器预计会快很多倍。我很确定这与代码或我的表模式声明有关,但我似乎无法在任何地方找到瓶颈。表架构如下所示:
CREATE TABLE Events (
ID varchar(38) primary key,
ownerName varchar(32) not null,
personID varchar(38) not null,
latitude float not null,
longitude float not null,
country varchar(64) not null,
city varchar(128) not null,
eventType varchar(8) not null,
year int not null,
foreign key (ownerName)
references Users (userName)
on delete cascade
on update cascade,
foreign key (ID)
references People (ID)
on delete cascade
on update cascade
);
执行插入的代码如下函数
public class EventAccessor {
private Connection handle;
...
public void insert(Event event) throws DataInsertException {
String query = "insert into Events(ID,ownerName,personID,latitude,longitude,country,"
+ "city,eventType,year)\nvalues(?,?,?,?,?,?,?,?,?)";
try (PreparedStatement stmt = handle.prepareStatement(query)) {
stmt.setString(1, event.getID());
stmt.setString(2, event.getUsername());
stmt.setString(3, event.getPersonID());
stmt.setDouble(4, event.getLatitude());
stmt.setDouble(5, event.getLongitude());
stmt.setString(6, event.getCountry());
stmt.setString(7, event.getCity());
stmt.setString(8, event.getType());
stmt.setInt(9, event.getYear());
stmt.executeUpdate();
} catch (SQLException e) {
throw new DataInsertException(e.getMessage(), e);
}
}
}
其中Event 是一个包含模式条目的类,DataInsertionException 是在 API 其他地方定义的简单异常。我被指示使用PreparedStatement,因为使用Statement 显然“更安全”,但我可以选择切换,所以如果它更快,我很乐意更改代码。我用来插入 122 个条目的函数实际上是 Event 对象数组的包装器,看起来像这样
void insertEvents(Event[] events) throws DataInsertException {
for (Event e : events) {
insert(e);
}
}
我现在愿意尝试任何方法来提高性能。
【问题讨论】:
标签: java sqlite optimization jdbc