原来的代码
public string Remove(string id) { using SqlConnection conn = new SqlConnection("server=.;database=dbo;uid=sa;pwd=123"); conn.Open(); SqlCommand cmd = new SqlCommand($"DELETE FROM Users WHERE Id = {id}",conn); cmd.ExecuteNonQuery(); return "1"; }
修改后的代码
public string Remove(string id) { using SqlConnection conn = new SqlConnection("server=.;database=dbo;uid=sa;pwd=123"); conn.Open(); SqlCommand cmd = new SqlCommand($"DELETE FROM Users WHERE Id = @Id",conn); SqlParameter sqlParameter = new SqlParameter("@Id",id); cmd.Parameters.Add(sqlParameter); cmd.ExecuteNonQuery(); return "1"; }
传多个参数时
public string Remove(string userNo,string userName) { using SqlConnection conn = new SqlConnection("server=.;database=dbo;uid=sa;pwd=123"); conn.Open(); SqlCommand cmd = new SqlCommand($"DELETE FROM Users WHERE UserNo = @UserNo AND UserName = @UserName",conn); SqlParameter sqlParameter = new SqlParameter[]{ new SqlParameter("@UserNo",userNo), new SqlParameter("@UserName",userName) }; cmd.Parameters.AddRange(sqlParameter); cmd.ExecuteNonQuery(); return "1"; }