我正在从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分钟。我有一个很好的谷歌,但我似乎无法发现我做错了什么。准备好的陈述是否不适合我的特定问题?
答案 0 :(得分:1)
当您想多次执行相同的查询时,会给出使用PreparedStatement的主要性能提升。数据库在准备语句时构造查询,然后在每次执行语句时重新使用它以避免开销。如果您只执行一次查询,那么使用PreparedStatement可能不会看到任何性能提升。
使用PreparedStatement的主要理由是防止SQL注入