如何在SQL Server中插入日期和时间 [英] How can I insert a date and time into SQL server
问题描述
我在C#中有一个问题是在sql server中保存日期和时间
我得到datetimepicker的日期,直到一切都很好,但是我将程序运行到maceando我收到错误将数据类型varchar转换为datetime 时出错。
我尝试更改日期设置,它只允许我保存日期
我尝试了什么:
Hi, I have a problem in C # to save the date and time in sql server
I get the date of a datetimepicker until everything is fine but when I run the procedure to the maceando I get the error "Error converting data type varchar to datetime."
And I tried changing the date settings and it only allows me to save the date
What I have tried:
private void Btn_Aceptar_Click_1(object sender, EventArgs e)
{
string cmd = string.Format("Execute SpInsertar_Cliente '{0}','{1}','{2}','{3}'",
this.Txt_Id_Cliente,
this.Txt_RasonSocial.Text.Trim(),
// parametro 3 con error
//////////////////////////////////////////////////////////////////////////////
// Prueva 1 no funsiona
// CONVERT(DATETIME,'" & Format(FPEDIDO, "yyyy-mm-dd hh:mm:ss") & "',102) , "
// Prueva 2 no funsiona
// Convert.ToDateTime(DTP_Aniversario.Value, "yyyy-mm-dd hh:mm:ss"),
// Prueva 3 no funsiona
// DTP_Aniversario.Value.ToString("m",CultureInfo.CreateSpecificCulture("en-us")),
// Prueva 4 funsiona esta generado una clase pero con la hora -> 00:00:00
Validacion.fechachange(DTP_Aniversario.Value),
////////////////////////////////////////////////////////////////////////////////
this.CkB_Bloqueado.Checked,
);
Utilidades.EjecSql(cmd, Frm_Login.Conexion);
Mensajeok("Se ingreso correctamente el registro");
}
//Clase para validar la fecha
////////////////////////////////////////////////////////////////////////
public class Validacion
{
public static string fechachange(DateTime fecha)
{
return fecha.ToString("yyyy-MM-dd HH':'mm':'ss");
}
}
推荐答案
正如Bryian Tan指出行
As Bryian Tan has indicated the line
return fecha.ToString("yyyy-MM-dd HH':'mm':'ss");
不正确。它可以是
return fecha.ToString("yyyy-MM-dd HH:mm:ss");
或可能
return fecha.ToString("u");
if you you使用标准日期和时间格式字符串 [ ^ ]
但是,而不是使用string.format构建命令(这可能使您容易受到SQL注入攻击)为什么不使用SqlParameters( SqlParameter类(System.Data.SqlClient) [ ^ ])
类似......(未经测试)
if you use the Standard Date and Time Format Strings[^]
However, instead of constructing the command using string.format (which can leave you susceptible to sql injection attacks) why not utilise SqlParameters (SqlParameter Class (System.Data.SqlClient)[^])
Something like ...(untested)
var cmd = New SqlCommand("Execute SpInsertar_Cliente @Client, @RasonSocail, @Aniversario, @Bloqueado");
cmd.Parameters.AddWithValue("@Client", this.Txt_Id_Cliente);
cmd.Parameters.AddWithValue("@RasonSocail",this.Txt_RasonSocial.Text.Trim());
cmd.Parameters.AddWithValue("@Aniversario", DTP_Aniversario.Value);
cmd.Parameters.AddWithValue("@Blqueado",this.CkB_Bloqueado.Checked);
示例1
Example 1
insert into table1(approvaldate)values('20120618 10:34:09 AM');
示例2
Example 2
insert table1 (approvaldate)
values (convert(datetime,'18-06-12 10:34:09 PM',5))
这篇关于如何在SQL Server中插入日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!