在C#中,我想编写一个包含smalldatetime
列的更新查询,我在Stackoverflow上看过几篇帖子,但是我找不到一个解决错误的帖子:
将字符串转换为smalldatetime数据类型时转换失败。
我有一个表RESERVAS
,有3列ID_RESERVA
(int
),LLEGADA
(smalldatetime
),SALIDA
({{ 1}})
代码:
smalldatetime
答案 0 :(得分:4)
那是因为你用单个刻度线包裹了你的参数。你对它进行编码的方式是尝试解析字符串文字而不是参数中的值。
string strQuery = "UPDATE " + DB_TABLENAME + " SET " +
"LLEGADA = CONVERT(smalldatetime, @LLEGADA, 126), " +
"SALIDA = CONVERT(smalldatetime, @SALIDA, 126) " +
"WHERE ID_RESERVA = @ID_RESERVA";
SqlCommand cmd = new SqlCommand(strQuery, con); // con = SqlConnection
cmd.Parameters.Add("@ID_RESERVA", SqlDbType.Int);
cmd.Parameters.Add("@LLEGADA", SqlDbType.SmallDateTime);
cmd.Parameters.Add("@SALIDA", SqlDbType.SmallDateTime);
cmd.Parameters["@ID_RESERVA"].Value = Convert.ToInt32(stringWithIdReserva);
cmd.Parameters["@LLEGADA"].Value = stringWithLLegada.Replace(" ", "T"); //Real string value: "2015-03-30 00:00:00"
cmd.Parameters["@SALIDA"].Value = stringWithSalida.InnerText.Replace(" ", "T"); //Real string value: "2015-04-01 00:00:00"
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}