0

我正在从 Access 数据库中的三个表中读取大量数据,大约 200 万行,可能是 100MB 的文本。我正在使用以下 SELECT 语句:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + databaseLocation + databaseName +";selectMethod=cursor; READONLY=true; TYPE=FASTLOAD";

con = DriverManager.getConnection(url);

String SQL = "SELECT ADDRESS_MODEL.ADDR_LINE_1, ADDRESS_MODEL.ADDR_LINE_2, LOCALITIES.NAME, ADDRESS_MODEL.SECONDARY_LOCALITY, ADDRESS_MODEL.POST_TOWN, ADDRESS_MODEL.COUNTY, BUILDINGS.ED_ID FROM (ADDRESS_MODEL LEFT JOIN BUILDINGS ON ADDRESS_MODEL.BUILDING_ID = BUILDINGS.BUILDING_ID) LEFT JOIN LOCALITIES ON BUILDINGS.LOCALITY_ID = LOCALITIES.LOCALITY_ID WHERE BUILDINGS.COUNTY_ID = " + county_ID;

Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(SQL);

这需要一段时间(大约 2 分钟),所以我想办法让它更快。我阅读了有关准备好的陈述并决定尝试制作一个。按照各种教程,我把它放在一起:

String SQL = "SELECT ADDRESS_MODEL.ADDR_LINE_1, ADDRESS_MODEL.ADDR_LINE_2, LOCALITIES.NAME, ADDRESS_MODEL.SECONDARY_LOCALITY, ADDRESS_MODEL.POST_TOWN, ADDRESS_MODEL.COUNTY, BUILDINGS.ED_ID FROM (ADDRESS_MODEL LEFT JOIN BUILDINGS ON ADDRESS_MODEL.BUILDING_ID = BUILDINGS.BUILDING_ID) LEFT JOIN LOCALITIES ON BUILDINGS.LOCALITY_ID = LOCALITIES.LOCALITY_ID WHERE BUILDINGS.COUNTY_ID = ?";

PreparedStatement prest = con.prepareStatement(SQL);
prest.setString(1, county_ID);

ResultSet result = prest.executeQuery();

它仍然有效,但现在需要超过 15 分钟。我有一个很好的谷歌,但我似乎无法发现我做错了什么。准备好的陈述是否不适合我的特定问题?

4

1 回答 1

1

当您想要多次执行相同的查询时,使用 PreparedStatement 可以获得主要的性能提升。数据库在准备好语句时构造查询,然后在每次执行语句时重新使用它以避免开销。如果您只执行一次查询,那么使用 PreparedStatement 可能不会看到任何性能改进。

使用 PreparedStatement 的主要论据是防止 SQL 注入

于 2012-08-06T19:50:43.010 回答