I know there are many questions like this already. I've been stuck on this all day. I'm running a query with a prepared statement from Java to mysql. It throws an exception because it returns an empty result set even though when I run the same query on phpmyadmin it returns some rows. My code is as follows:
public static Integer returnImportLog(String filename,String importLogs,int acc_id){
int id_out=0;
ArrayList<Integer> ids = new ArrayList<Integer>();
try{
String myUrl = "jdbc:mysql://localhost:3307/blahblah";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(myUrl,"root","");
String query2 = "SELECT DISTINCT `id` FROM `"+importLogs+ "` "
+ "WHERE `file`=? AND `acc_id`= ?";
PreparedStatement statement=conn.prepareStatement(query2);
statement.setString(1,filename);
statement.setInt(2,acc_id);
//System.out.println();
ResultSet rs = statement.executeQuery();
if (rs.next())
{
int user_id = rs.getInt("id");
ids.add(user_id);
}
id_out=(Integer)ids.get(0);
conn.close();
statement.close();
rs.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
e.printStackTrace();
}
return id_out;
It gives the following error:
"Got an exception!
Index: 0, Size: 0 ava.lang.IndexOutOfBoundsException: Index: 0, Size: 0 t java.util.ArrayList.rangeCheck(Unknown Source) at java.util.ArrayList.get(Unknown Source) at Details.returnImportLog(Details.java:277)"
When I run the sql generated by the prepared statement
SELECT DISTINCT
id
FROMpwc_import_logs
WHEREfile
='11111Spanners.csv' ANDacc_id
= 1"
on phpmyadmin MySQL I get the following result 2 results in the row.
Any help would be much appreciated....its wrecking my head and i'm sure its something trivial
The query didn't execute, thus resulting empty result set rs
. So, the arraylist ids
won't be having any data. But, you are trying to read from arraylist ids.get(0)
which is throwing IndexOutOfBoundsException. Can you please try removing (backtick)` sign in query string and try again?