2

I am having difficulty figuring out how to send one/multiple rows from my jtable in Java Netbeans to my Microsoft SQL Server. Any suggestions? Below is my code

       //dataTable2
      else if (tabledata == "Table 2")
      {
          TableModel dataModel1 = receiptTable.getModel();
          Object[] col = new Object[3];


            DefaultTableModel dataModel2 = (DefaultTableModel) dataFrame.dataTable2.getModel();

            for(int i = 0; i < receiptTable.getRowCount(); i++)
            {
                col[0] = dataModel1.getValueAt(i, 0);
                col[1] = dataModel1.getValueAt(i, 1);
                col[2] = dataModel1.getValueAt(i, 2);
                try{
                    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                    String url = "jdbc:sqlserver://localhost:1433;databaseName=Customer_Data;integratedSecurity=true";

                    Connection con = DriverManager.getConnection(url);
                    String query = "insert into ContactInfo(name, address, email)values(?,?,?)";
                    PreparedStatement pst = con.prepareStatement(query);
                    pst.setString(1, (String) col[0]);
                    pst.setString(2, (String) col[1]);
                    pst.setString(3, (String) col[2]);
                    pst.executeUpdate();
                    JOptionPane.showMessageDialog(null, "Inserted Successfully!");

                }
                catch(Exception e){
                   JOptionPane.showMessageDialog(null, e);
                }
                dataModel2.addRow(col);
            }
            orderSubmit.requestFocusInWindow();
            revalidate();
            repaint();
            dataModel2.fireTableDataChanged();

      }

When I run this I get below:

Class Cast Exception

  • How is a `Object` a `String`? – MadProgrammer Apr 12 '18 at 01:28
  • You are trying an `Object` that is an `Integer` to a `String`. That is not possible. Either use `pst.setObject`, or perform correct conversions. – Mark Rotteveel Apr 12 '18 at 07:43
  • Thank you for the feedback, I was able to correct my error. Here is the code I used to solve it: Instead of 'pst.setString(1, (String) col[0]);', I did 'pst.setString(1, col[0].toString()); and it worked – Steve Filus Apr 20 '18 at 03:06

0 Answers0