简体   繁体   中英

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

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. 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.

Next to that, you can also use a DateTimePicker instead of textbox, can't you ?

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 " "?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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