java.sql.SQLException参数索引超出范围

时间:2012-11-10 05:15:23

标签: java mysql mysql-error-1064

在使用此代码时,它会显示java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

private void cmd_searchActionPerformed(java.awt.event.ActionEvent evt) {                                           
try{

 String sql = "select * from STD where Name like '%?%' ";
      pst=conn.prepareStatement(sql);
      pst.setString(1,TXT_STUDENTNAME.getText());
      String value=TXT_STUDENTNAME.getText();
      rs=pst.executeQuery();
       jTable1.setModel(DbUtils.resultSetToTableModel(rs));

             }catch(Exception e){
       JOptionPane.showMessageDialog(null,e);
   }        
}     

我如何从此例外中恢复?

2 个答案:

答案 0 :(得分:2)

尝试从sql中删除通配符并将其添加到值:

String sql = "select * from STD where Name like ? ";
pst=conn.prepareStatement(sql);
pst.setString(1,"%"+TXT_STUDENTNAME.getText()+"%");

Similar question here

答案 1 :(得分:0)

private void cmd_searchActionPerformed(java.awt.event.ActionEvent evt) {                                           
try{

 String sql = "select * from STD where Name like '%?%' ";
      String strStudentName = TXT_STUDENTNAME.getText();
      pst=conn.prepareStatement(sql);
      pst.setString(1,strStudentName );
      rs=pst.executeQuery();
       jTable1.setModel(DbUtils.resultSetToTableModel(rs));

             }catch(Exception e){
       JOptionPane.showMessageDialog(null,e);
   }        
}  

我认为这会对你有帮助..

String strStudentName = TXT_STUDENTNAME.getText(); pst.setString(1,strStudentName);