如何使用Java将行插入Microsoft SQL数据库

时间:2018-04-12 00:56:44

标签: java sql sql-server jdbc sql-insert

我很难弄清楚如何从Java Netbeans中的jtable向我的Microsoft SQL Server发送一行/多行。有什么建议?以下是我的代码

       //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();

      }

当我跑步时,我得到以下内容:

Class Cast Exception

0 个答案:

没有答案