我正在尝试创建一个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();
}
}
}
但是当我这样做时,我正在努力调整代码,并希望得到一些帮助。如果需要,我可以提供更多信息。我希望新函数将要编辑的行的唯一标识符的输入作为一个数组 - 值加上表示主键的列的名称 - 用于要删除的行,以及表名。
答案 0 :(得分:2)
您需要从参数中获取值并将它们放入格式正确的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();
}
}
}
这种方法存在很多性能和安全问题,但我认为你是出于教育目的而这样做的吗?