简体   繁体   中英

JAVA MYSQL prepared statement giving empty resultset even though query works in mysql admin

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 FROM pwc_import_logs WHERE file ='11111Spanners.csv' AND acc_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

Try to replace ` with '. I had some problems with this difference in the past and I guess replacing them could solve the issue. :)

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM