简体   繁体   English

SQL Server的DateTime转换错误asp.net

[英]DateTime Conversion Error asp.net with sql server

<asp:TextBox ID="txtBox" runat="server">
</asp:TextBox>
<asp:CalendarExtender ID="ce" runat="server" TargetControlID="txtBox" Format="dd-MMM-yyyy">
</asp:CalendarExtender>

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection239"].ToString()))
{
    SqlCommand cmd = new SqlCommand("insert into tbl_testing(dttm) values('"+DateTime.Parse(txtBox.Text)+"')", con);
    con.Open();
    cmd.ExecuteNonQuery();
}

when i execute following error is coming. 当我执行以下错误时。 In which format should I send the date to sql server 我应该以哪种格式将日期发送到SQL Server

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. 从char数据类型到datetime数据类型的转换导致超出范围的datetime值。 The statement has been terminated. 该语句已终止。 Thanks in advance 提前致谢

Use parameters in your query, instead of string concatenation. 在查询中使用参数,而不是字符串连接。 Not only will your datetime problems be gone, but your query will also not be vulnerable to sql injection. 不仅您的日期时间问题将消失,而且您的查询也将不易受到sql注入的攻击。

Next to that, you can also use a DateTimePicker instead of textbox, can't you ? 除此之外,您还可以使用DateTimePicker代替文本框,对吗?

var command = conn.CreateCommand();
command.CommandText = "insert into tbl_testing(thecol) values(@p_someDate)";
command.Parameters.Add ("@p_someDate", SqlDbType.DateTime).Value = datetimePicker.Value;
command.ExecuteNonQuery();

Use following code instead: 请使用以下代码:

        SqlCommand cmd = new SqlCommand("insert into tbl_testing(dttm) values(@dttm)", con);
        cmd.Parameters.AddWithValue("@dttm", DateTime.Parse(txtBox.Text));
        con.Open();
        cmd.ExecuteNonQuery(); 

只需通过SqlParameter传递值,就永远不要使用字符串连接。

mm-dd-yyyyThh:mm:ss

Make sure the server (local or otherwise) is using the correct time. 确保服务器(本地或其他)使用正确的时间。 For eg if its British or American. 例如,如果它是英国或美国。 Dates are also wrapped in ' '. 日期也包裹在“”中。 It seems you are wrapping it in " "? 看来您将其包装在“”中?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM