C# 从数据库建议中删除

C# 从数据库建议中删除,c#,C#,我正在尝试创建一个C#delete函数。这就是我到目前为止所拥有的,尽管我想对其进行调整,使其像下面的伪代码一样工作 新函数的伪代码 //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

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

新函数的伪代码

//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? 

//}
//}
//公共bool delete(字典id、字符串tableName)
//{
//读取器或其他对象
//开放式会议
//语句获取要编辑行的主键的输入
//作为1的数组,值加上表示主键的列的名称
//用于要删除的行以及表名
//联系
//执行
//返回布尔?
//}
//}
我所尝试的:

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();
        }              
    }
}
public bool Delete(字典id,字符串tableName)
{            
//读取器或其他对象
//开放连接
使用(SqlConnection conn=newsqlconnection(ConnectionString))
{    
conn.Open();
使用(SqlCommand cmd=newsqlcommand(“从tableName中删除,其中id=id”,conn))
{
cmd.ExecuteNonQuery();
}              
}
}

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

您需要从参数中获取值,并将它们放入格式正确的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();
     }
  }
}

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

请澄清您的具体问题,或添加其他详细信息,以突出您需要的内容。正如目前所写的,很难准确地说出你在问什么。请参阅页面以获得澄清此问题的帮助。好吧,我遇到的问题是如何调整我当前的代码以适应新的用途,我正在努力解决的部分是语句。到目前为止,我看到的所有问题可能都是基本语法问题。您是否阅读了支持文档?一旦你习惯了阅读,它就会非常有用。通过简单的谷歌搜索就可以轻松解决的语法问题在这里通常不太受欢迎,尤其是在这个网站上也有很多重复的问题。嗨,Michael,谢谢你的帮助,好吧,我现在来看看,虽然我认为这些功能比基本功能稍微难一些。好吧,我来试试,是的,在这个阶段我不介意。它说并不是所有的代码路径都返回一个值,所以我应该如何在最后返回一个boll-en来表示delete有效?是的,这是有意义的,或者让方法暂时无效。问题是我必须使用public bool delete(Dictionary id,string tableName),所以我不能使用该方法,但感谢您的帮助