在開發中,我們經常會遇到需要查詢大量數據的情況,為了提高查詢速度,我們可以采用以下方法:
1、使用索引
CREATE INDEX index_name ON table_name(column_name);
2、使用連接池
//使用Druid連接池 public class DruidUtil { private static DataSource dataSource = null; static { try { Properties properties = new Properties(); properties.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties")); dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } }
3、批量操作
Connection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); for (int i = 0; i< 10000; i++) { StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO test (name, age) VALUES ('name").append(i).append("', ").append(i).append(")"); stmt.addBatch(sql.toString()); } stmt.executeBatch(); conn.close();
4、使用PreparedStatement
Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM test WHERE name = ?"); for (int i = 0; i< 100; i++) { pstmt.setString(1, "name" + i); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getInt("id")); } } conn.close();
5、分頁查詢
SELECT * FROM table_name LIMIT start_index, page_size;
通過以上方法,我們可以提高jdbc查詢mysql的速度,同時也可以避免一些常見的性能問題。