2

Conversion failed when converting the nvarchar value 'XX' to data type int. im having these error and i dont know what to do with it. please help me. THANKS. :D

   btnNewButton_3.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    String value1=textField_7.getText();
                     try{

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                         String connectionURL = "jdbc:sqlserver://;Database='';user='';password='';";
                         Connection con = DriverManager.getConnection(connectionURL);
                       PreparedStatement pst =null;
                            //Statement stmt=con.createStatement();

       //PreparedStatement pst=con.prepareStatement("select * from inventory where Id=? or Name=? ");
                        String sql ="select * from inventory where Id=? or Name=? ";
                        pst=con.prepareStatement(sql);
                        pst.setString(1, textField_7.getText());
                        pst.setString(2, textField_7.getText());


                     ResultSet rs = pst.executeQuery();
                     if(value1.equals("")){
                          reloadData();
                          model.fireTableDataChanged();
                          JOptionPane.showMessageDialog(null,"Please Enter a Name or Id of the Item","ERROR",JOptionPane.ERROR_MESSAGE);

                      }else{  


                                  table.setModel(DbUtils.resultSetToTableModel(rs));
                  }

                           }


                     catch(Exception e1){e1.printStackTrace();}

                }


            });
Rohan21
  • 353
  • 5
  • 9
  • 24

2 Answers2

4

Try changing the SQL Statement from

select * from inventory where Id=? or Name=?

to

select * from inventory where CAST(Id AS NVARCHAR(50))=? or Name=?

The problem is that you are using the same text field to compare to both Id and Name, so if you were to enter Rohan into the text field it would try to convert it to an INT to compare to Id, in which case the statement would fail.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
0

Assuming that your Id Column is integral, you're getting this error because you are trying to assign it a string. If the field is integral, parse the textField to an int and then use setInt

pst.setInt(1, parsedInt);
Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285