简体   繁体   中英

Conversion failed when converting date and/or time from character string

I'm trying to store a datetime into a SQL database. I use datetime2(0) variable for that purpose.

But i always get this exception :

Conversion failed when converting date and/or time from character string

Here's my code that generates the error :

protected void InsertDB(string title, string desc, string cat, string path)
{
    string now = DateTime.Now.ToString("dd-MM-yyyy h:mm:ss tt");
    title = title.Length == 0 ? "Untitled" : title;
    cat = cat.Length == 0 ? "Uncategorized" : cat;
    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(cs))
    {
        try
        {                    
            SqlCommand cmd = new SqlCommand(@"INSERT INTO gallery (img_title, img_desc, img_cat, img_date, img_path)
                                            VALUES (@title, @desc, @cat, @date, @path)", con);
            con.Open();
            cmd.Parameters.AddWithValue("@title", title.Trim());
            cmd.Parameters.AddWithValue("@desc", desc.Trim());
            cmd.Parameters.AddWithValue("@cat", cat.Trim());
            cmd.Parameters.AddWithValue("@date", now.Trim());
            cmd.Parameters.AddWithValue("@path", path.Trim());
            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                msg_lbl.Visible = true;
                msg_lbl.Text = "New Image is uploaded.";
                title_txt.Text = "";
                desc_txt.Text = "";
                cat_txt.Text = "";                        
            }
            else
            {
                msg_lbl.Visible = true;
                msg_lbl.Text = "Error occured.";
            }
        }
        catch (SqlException ex)
        {
            msg_lbl.Visible = true;
            msg_lbl.Text = ex.Message; //I get this exception here
        }
        catch (Exception ex)
        {
            msg_lbl.Visible = true;
            msg_lbl.Text = ex.Message;
        }

    }

The error must be when passing the variable "now" in the sql query. If the column Img_date is a datetime field then you must pass the value as aa datetime not as a string. Try assigning the value Datetime.Now to the parameter @date :

cmd.Parameters.AddWithValue("@date", DateTime.Now);

When using DateTime2 columns, you need to specifically set the parameter type - it defaults to DateTime with AddWithValue .

Try this:

SqlParameter parm = cmd.Parameters.Add("@date", SqlDbType.DateTime2);
parm.Value = DateTime.Now;

According to MSDN:

The @date parameter could map to a date, datetime, or datetime2 data type on the server. When working with the new datetime data types, you must explicitly set the parameter's SqlDbType property to the data type of the instance. Using Variant or implicitly supplying parameter values can cause problems with backward compatibility with the datetime and smalldatetime data types.

http://msdn.microsoft.com/en-us/library/bb675168.aspx

Hope this helps.

因为tsql不会接受'tt'格式说明符,所以出现了该错误。

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