【发布时间】:2014-08-27 09:48:31
【问题描述】:
我正在尝试使用 Java 连接到我的 MySQL 数据库。代码如下:
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
java.sql.Statement stmt = connection.createStatement();
long startTime = System.currentTimeMillis();
stmt.execute("SELECT row_1, row_2, row_3, row_4 FROM dataset where row_5 is null and row_6 is null limit 100");
long endTime = System.currentTimeMillis();
System.out.println("That took " + (endTime - startTime) + " milliseconds");
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getString("row_1"));
}
stmt.close();
表“数据集”有 500 万行,并在主索引(row_1、row_2、row_3、row_4)和第二个索引(row_5 和 row_6)上建立索引。
未缓存,此查询使用 SequelPro for Mac(数据库管理软件)需要 1.9 毫秒。但是,当我在 Java 中运行上面的代码时,大约需要 1800 毫秒(未缓存)。请让我知道是 Java 速度慢还是我可以做些什么来优化 Java 中的查询,因为使用 SequelPro 或使用其他脚本语言可以很好地工作。
【问题讨论】:
-
当您在 sequelPro 中执行查询时,您是否像在代码中那样考虑了与数据库的连接时间?
-
你如何衡量时间?
-
MySQL 在 mac 上运行速度较慢。尝试用linux(centos, ubuntu)制作虚拟机并在上面安装mysql。
-
@Pedromarce - 是的,我只计时了 stmt.execute() 行。
-
@KarolS - 我使用 System.currentTimeMillis(); 测量时间; (见编辑代码)