【问题标题】:Delete in JTable with connect SQL?使用连接 SQL 在 JTable 中删除?
【发布时间】:2020-07-12 05:37:09
【问题描述】:

我想删除在 Id 列中按下时选择的整行数据,因此我尝试使用此代码,但出现此错误:“java.sql.SQLException: Conversion failed when convert the nvarchar value 'T123' to数据类型 int. " 'T123' 是 Id 的数据

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

【问题讨论】:

    标签: java


    【解决方案1】:

    根据您的描述,您的数据库表的 ID 列是 NVCHAR 类型,但您将其设置为 int。这里要注意的另一点是,您需要根据所选行 ID 获取 ROW ID,然后在您的 ps 语句中使用 setString。

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

    【讨论】:

    • 如何在 ps.setString(1, idString) 中声明 idString ?因为 tb.getSelectedRow() 的值是整数。
    • 我解决了这个错误,但现在我仍然无法删除数据。
    • 您可能想检查idString 值。另外,有几点观察: 1. ps.executeUpdate(); 将返回 no。删除的记录数,如果没有删除,则为 0,但从不 -1。 2.url实际上不是url而是driver 3.db不是数据库而是jdbcUrl
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2023-03-04
    • 2017-07-02
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    相关资源
    最近更新 更多