【问题标题】:delete sql not deleting删除sql不删除
【发布时间】:2011-02-13 12:00:01
【问题描述】:

我正在尝试从我的表中删除一个事件。但是我似乎无法让它工作。 我的 SQL 语句是:

  public void deleteEvent(String eventName){
    String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";
    db.update(query);
    System.out.println (query);
}

使用 MySQL 数据库

【问题讨论】:

  • db 是什么,update 是做什么的,我不知道,但我相信如果你读到这个:oreilly.com/catalog/javadata/chapter/ch04.html,并正确地写下你的查询,你会得到想要的结果。
  • 嗨。 db 是我的数据库,更新应该更新我的查询(本质上)
  • “db 是我的数据库”是什么意思...你是如何用一个类来抽象你的数据库的?
  • 很惊讶没有人提到明显的 SQL 注入可能性/事件名称包含 ' 的问题。使用参数化查询。

标签: java sql mysql netbeans


【解决方案1】:

尝试使用以下方法:

String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";

        try {
            Connection con = getConnection();
            Statement s = con.createStatement();

            s.execute(query);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

您必须对 getConnection() 方法进行编码才能返回有效的数据库连接。

【讨论】:

    【解决方案2】:

    我建议使用Statement.executeUpdate 方法,因为它返回一个整数。因此,在执行此删除查询后,如果您确实删除了任何记录,您还将获得信息(在这种情况下,您希望此方法返回 1,因为您使用的是 LIMIT=1)。我还建议您在不需要时立即关闭 Statement,这是框架实现:

    private void performDelete(Connection conn, String deleteQuery, int expectedResult) throws SQLException {
        Statement stmt = conn.createStatement();
        int result = -1;
        try {
            result = stmt.executeUpdate(deleteQuery);
            if(result != expectedResult) {
                //Here you can check the result. Perhaps you don't need this part
                throw new IllegalStateException("Develete query did not return expected value");
            }
        } catch(SQLException e) {
            //Good practice if you use loggers - log it here and rethrow upper.
            //Or perhaps you don't need to bother in upper layer if the operation
            //was successful or not - in such case, just log it and thats it.
            throw e;
        } finally {
            //This should be always used in conjunction with ReultSets.
            //It is not 100% necessary here, but it will not hurt
            stmt.close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 2013-08-31
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2022-07-22
      • 1970-01-01
      相关资源
      最近更新 更多