I am trying to read a column from a sql database in java, I want the result to be returned in an array. Here is the function:
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; }
This is pretty slow. It takes 1.5 seconds with my sqlite database. Is this the standard way to read a column, or am I doing something wrong? This is a bottleneck in my application, so I need it to be as fast as possible.
Edited: Thank you. I just found out that ArrayList is not causing a problem. The bottleneck should be in the sql part: If I download the data in just 10 days, it will take as much time as loading the data in 10 years. So I have to improve my sql, but how ??
Here's the improved code:
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; }
source share