C# 我需要写什么函数才能从表中删除?
我的功能是向表中添加:C# 我需要写什么函数才能从表中删除?,c#,sql,C#,Sql,我的功能是向表中添加: public int insertHistory(string title, string description, int isDone, int userId) { int s = -1; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "INSERT
public int insertHistory(string title, string description, int isDone, int userId)
{
int s = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "INSERT INTO History(title,description,isDone,userId) VALUES(@param1,@param2,@param3,@param4)";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("@param1", SqlDbType.NVarChar, 10).Value = title;
cmd.Parameters.Add("@param2", SqlDbType.NVarChar, 400).Value = description;
cmd.Parameters.Add("@param3", SqlDbType.Int).Value = isDone;
cmd.Parameters.Add("@param4", SqlDbType.Int).Value = userId;
cmd.CommandType = CommandType.Text;
s = cmd.ExecuteNonQuery();
}
}
return s;
}
我需要编写什么代码才能按标题或其他内容从表中删除?您已要求使用标题删除,下面是如何执行此操作
public int deleteHistory(string title)
{
int s = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "DELETE FROM History WHERE Title = @title)";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("@title", SqlDbType.NVarChar, 10).Value = title;
s = cmd.ExecuteNonQuery();
}
}
return s
}
但是,通过这种方式,您可能会删除比您想要的更多的记录。如果两个或多个记录具有相同的标题,您将删除具有相同标题的所有记录。您还可以通过将UserID添加到where条件和将相对参数添加到parameters集合来缓解此问题
"DELETE FROM History WHERE Title = @title AND UserID = @uid"
因此,您只删除特定用户的标题,但这仍然不安全。如果您的表有一个标识列,并且在读取记录时从该列中检索值,则可以将该唯一值传递给查询,并仅删除一条记录
"DELETE FROM History WHERE HistoryID = @hid"
当您使用SqlConnection和普通SQL语句时。您需要在代码中调用
Delete
语句:
public void DeleteHistory(string title)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = "delete from History where title= @title";
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("@title", SqlDbType.NVarChar).Value = title;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}
您应该查找DELETE.OT以了解自己的健全性,请命名您的参数。它的工作原理是一样的,但是您可以很容易地识别每个参数的含义——即使您必须在下个月的这个方法中修复某些内容,请参见该方法旁边的页面