【问题标题】:Delete from Database advice从数据库建议中删除
【发布时间】:2015-12-17 14:42:28
【问题描述】:

我正在尝试创建一个 C# 删除函数。这就是我目前所拥有的,尽管我想将其调整为像下面的伪代码一样工作。

新功能的伪代码

//public bool delete(Dictionary <string, string> id, string tableName)
//{

//reader or another object

//open conenction 

//statement takes input of the primary key of the row to be edited
//as an array of one, the value plus the name of the column representing the primary key
//for the row to be deleted, as well as the table name 


//connection

//excute 

//return bool? 

//}
//}

我尝试过的:

public bool Delete(Dictionary <string, string> id, string tableName)
{            
    //reader or another object            

    //open connection 
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {    
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("DELETE FROM tableName WHERE id=id", conn))
        {
            cmd.ExecuteNonQuery();
        }              
    }
}

但是在这样做时,我正在努力调整代码,希望能得到一些帮助。如果需要,我可以提供更多信息。我希望新函数将要编辑的行的唯一标识符的输入作为一个数组 - 值加上表示主键的列的名称 - 用于要删除的行以及表名字。

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。
  • 好的,我遇到的问题是如何调整我当前的代码以适应新的目的,我正在努力解决的部分是声明。
  • 到目前为止我看到的所有问题都是基本语法问题。您是否阅读了支持文档? MSDN 一旦你习惯阅读它就会非常有用。可以通过简单的 Google 搜索轻松解决的有关语法的问题通常在此处很少收到,尤其是即使在此站点上也有许多重复项。
  • 嗨,Michael,感谢您的帮助,好的,我现在看看,虽然我认为这些功能比基本功能稍微难一些。

标签: c#


【解决方案1】:

您需要从参数中获取值并将它们放入格式正确的 sql 字符串中,如下所示:

public bool Delete(string id, string column, string table)
{
  using (SqlConnection conn = new SqlConnection(ConnectionString))
  {
     conn.Open();
     var query = String.Format("DELETE FROM {0} WHERE {1}='{2}'", table,column, id)
     using (SqlCommand cmd = new SqlCommand(query))
     {
          cmd.ExecuteNonQuery();
     }
  }
}

这种方法存在许多性能和安全问题,但我认为您这样做是出于教育目的?

【讨论】:

  • 好的,我会试一试,是的,在这个阶段我不介意。它说并不是所有的代码路径都返回一个值,那么我如何在最后返回一个 boll en 来表示删除已经起作用?
  • 是的,这是有道理的,或者暂时使该方法无效。
  • 问题是我必须使用 public bool Delete(Dictionary id, string tableName) 所以我不能使用那个方法但是谢谢你的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多