java setString() not working

有些话、适合烂在心里 提交于 2021-02-02 10:01:16

问题


try{is = new FileInputStream(new File(s));
        PreparedStatement ps; 
        ps= cn.prepareStatement("Update instructor set name ='?' ,gender ='?', image ='?' where instructorID =?");
          JOptionPane.showMessageDialog(null, "5");
        ps.setString(1,name);
          JOptionPane.showMessageDialog(null, "4");
            ps.setString(2,gender);
            JOptionPane.showMessageDialog(null, "3");
            ps.setBlob(3, is);
            JOptionPane.showMessageDialog(null, "2");
          ps.setString(4, iden);
          JOptionPane.showMessageDialog(null, "1");
            ps.executeUpdate();
            JOptionPane.showMessageDialog(null, "successfully updated");
        }catch(Exception e ){
            JOptionPane.showMessage(null,"error1");
        }

So I want to insert these variables to the prepared statement, however I'm getting an error. After adding those JOptionPanes to debug, the program shows "5", and then "4" and then "error1". Which I think means that the line ps.setString(2,gender); failed to execute. However, I cannot find where did I get it wrong. Could anyone help?


回答1:


Remove quotes around question marks. Otherwise, '?' would be interpreted as a string literal with a single question mark in it:

ps= cn.prepareStatement("Update instructor set name =? ,gender =?, image =? where instructorID =?");

Currently, JDBC thinks that your query has a single parameter, corresponding to the question mark at the end. Trying to set parameter number two causes the exception.



来源:https://stackoverflow.com/questions/45770221/java-setstring-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!