我想在Java中从SQL数据库中读取一个列,并希望结果以数组形式返回。以下是函数:
public static double[] open(Connection conn,String symbol,int startdate,int enddate) throws SQLException {
int id = database.get_stockid(conn, symbol);
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select price_open from stock_data where stock_id="+id+" and date>="+startdate+" and date<="+enddate+";");
ArrayList<Double> data = new ArrayList<Double>();
while(rs.next()) {
data.add(rs.getDouble("open"));
}
double[] data1 = new double[data.size()];
for(int a = 0; a < data1.length; ++a) {
data1[a]=data.get(a);
}
return data1;
}
这很慢。在我的sqlite数据库中需要1.5秒钟。这是读取一个列的标准方法吗?还是我做错了什么?这是我的应用程序瓶颈,所以我需要尽可能快地解决它。
编辑: 谢谢。我刚刚发现ArrayList并不是问题的原因。瓶颈一定在sql部分: 如果我只加载10天的数据,它花费的时间与加载10年的数据一样长。所以我必须改进我的sql,但怎么做呢?
以下是改进后的代码:
public static double[] open(Connection conn,String symbol,int startdate,int enddate) throws SQLException {
int id = database.get_stockid(conn, symbol);
PreparedStatement stat = conn.prepareStatement("select price_open from stock_data where (stock_id="+id +") and (date between "+startdate+" and "+enddate+");");
ResultSet rs = stat.executeQuery();
ArrayList<Double> data = new ArrayList<Double>();
while(rs.next()) {
data.add(rs.getDouble(1));
}
double[] data1 = new double[data.size()];
for(int a = 0; a < data1.length; ++a) {
data1[a]=data.get(a);
}
return data1;
}
price_open
,但结果集使用了getDouble("open")
。这样做是否能按预期工作?另外,你一次获取了多少行数据? - FThompsonArrayList
转换为数组。要么更改open
的返回类型为List<Double>
,要么使用ArrayList
的toArray
方法,或者(最好的方法)在第一个循环内或甚至在数据库中进行计算。这将避免大部分数据传输和额外的Double
包装开销。 - A.H.PreparedStatement
,并且没有实现提供给你的所有建议。 - Adam Siemion