关于如何在SQL中配置多个Get,我感到非常困惑。论坛中的答案非常分散,到目前为止,我还没有能够实现下面代码的解决方案。我知道它不应该太复杂,但我不能。我的代码如下。非常感谢你。
[HttpGet]
[Route("cliente/{paramOne}/{paramTwo}")]
public HttpResponseMessage GetNomeNasc(string paramOne, string paramTwo)
{
try
{
Cliente cliente = null;
using (SqlConnection connection = new SqlConnection(this.ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "select id, nome, datanascimento, nascidoEm, email from clientes where nome =" + @paramOne + " and nascidoEm = " + @paramTwo;
command.Parameters.AddWithValue(paramOne, paramTwo);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
cliente = new Cliente()
{
Id = reader["id"] == DBNull.Value ? 0 : Convert.ToInt32(reader["id"]),
Nome = reader["nome"] == DBNull.Value ? string.Empty : reader["nome"].ToString(),
NascidoEm = reader["nascidoEm"] == DBNull.Value ? string.Empty : reader["nascidoEm"].ToString(),
DataNascimento = reader["datanascimento"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(reader["datanascimento"]),
Email = reader["email"] == DBNull.Value ? string.Empty : reader["email"].ToString()
};
}
}
connection.Close();
}
return Request.CreateResponse(HttpStatusCode.OK, cliente);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
根据底层数据库驱动程序,您可以使用命名或匿名参数。
您的问题是,您没有添加单个Parameters.AddwithValue(string name, Object object)
期望参数名称和要插入的值。看看definition of this function
更好的方法是:
command.Parameters.Add("@paramOne", DbType, size).Value = paramOne
您必须根据应添加值的单个列所允许的内容进行调整。看看here。
例如,我们想要插入一个需要整数的列,您将拥有以下行
command.Parameters.Add("@paramOne", SqlDbType.Integer).Value = paramOne
请注意,您必须单独添加参数。根据Db驱动程序,您必须按照(匿名)中引用的顺序执行此操作,或者可以按名称引用它,并且顺序无关紧要。
您还可以使用Parameters.AddRange()函数添加值数组或预先构造的SqlParameters。