Search code examples
javamysqlblob

ArrayIndexOutOfBoundsException while saving a 3gp file in MySQL


My code is:

psmnt = conn.prepareStatement("INSERT INTO upload_data(user_id,photo,audio) " + "values(?,?)");
psmnt.setLong(1, userId);   
fis = new FileInputStream(photoFile);
psmnt.setBinaryStream(2, (InputStream) fis, (int) (photoFile.length()));
fisAudio =  new FileInputStream(audioFile);
psmnt.setBinaryStream(3, (InputStream) fisAudio, (int) (audioFile.length()));
int s = psmnt.executeUpdate();

The type of audio in the MySQL database is a blob.

Exception is:

java.lang.ArrayIndexOutOfBoundsException: 2
    at com.mysql.jdbc.PreparedStatement.setBinaryStream(PreparedStatement.java:2089)
    at com.test.dao.TestDao.saveTestDetails1(TestDAo.java:154)
    at com.test.servlet.UploadImage.doPost(UploadImage.java:131)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)

How to resolve this?


Solution

  • you have only two parameters (question marks) in your SQL statement, but you're trying to bind the binary stream to the 3rd, not existing one. change your SQL statement like this:

    psmnt = conn.prepareStatement("INSERT INTO upload_data(user_id,photo,audio) "
                            + "values(?,?,?)");
    
    fisAudio =  new FileInputStream(audioFile);
    // you should bind something to the first and second ? marks too!
    psmnt.setLong(1, 12345L);
    psmnt.setString(2, "this is my photo");
    psmnt.setBinaryStream(3, (InputStream) fisAudio, (int) (audioFile.length()));
    int s = psmnt.executeUpdate();