0

I want to delete data whole row i choose when i press in the Id's column , so i try with this code but i have this error : "java.sql.SQLException: Conversion failed when converting the nvarchar value 'T123 ' to data type int. " 'T123' is a Id's data

 if (e.getSource() == delete) //button delete {
        int ret = JOptionPane.showConfirmDialog(this, "Do you want to delete?", "Confirm", JOptionPane.YES_NO_OPTION);
        if (ret != JOptionPane.YES_OPTION) {
            return;
        }
        Connection c = null;
        PreparedStatement ps = null;
        String url = "net.sourceforge.jtds.jdbc.Driver";
        int id = tb.getSelectedRow();
        try {
            Class.forName(url);
            String db = "jdbc:jtds:sqlserver://DUCTHANG:1433/student";
            c = DriverManager.getConnection(db, "username", "password");
            ps = c.prepareStatement("Delete From info where ID = ?");
            ps.setInt(1, id); //first column's value was choose in table
            ret = ps.executeUpdate();
            if (ret != -1) {
                JOptionPane.showMessageDialog(this, "This Student has been deleted");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (c != null) {
                    c.close();
                }
                if (ps != null) {
                    ps.close();
                }
            } catch (Exception ex2) {
                ex2.printStackTrace();
            }
        }
    }

1 Answers1

0

Based on what you described, your database table's ID column is NVCHAR type but you are setting it to int. Another point to note here is, you need to get the ROW ID based on the selected row ID and then use setString on your ps statement.

int id = tb.getSelectedRow();
// Now, get respective DB Row ID into String idString and then use the following
// statement in place of ps.setInt(1, id);
ps.setString(1, idString);
  • how can i declare idString in ps.setString(1, idString) ? because the value of tb.getSelectedRow() is integer. – Đức Thắng Jul 12 '20 at 06:14
  • Please refer to (https://stackoverflow.com/questions/29345792/java-jtable-getting-the-data-of-the-selected-row) – Hitesh A. Bosamiya Jul 12 '20 at 06:35
  • i was solve this error but now i still can't delete the data. – Đức Thắng Jul 12 '20 at 08:35
  • You may like to check the `idString` value. Also, couple of observations: 1. `ps.executeUpdate();` will return no. of records deleted or 0 if not deleted any but never -1. 2. `url` is not actually an `url` but `driver` 3. `db` is not database but `jdbcUrl` – Hitesh A. Bosamiya Jul 12 '20 at 11:00