簡體   English   中英

從字符串轉換日期和/或時間時轉換失敗

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

我正在嘗試將datetime時間存儲到SQL數據庫中。 我為此使用datetime2(0)變量。

但是我總是得到這個異常:

從字符串轉換日期和/或時間時轉換失敗

這是生成錯誤的代碼:

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;
        }

    }

該錯誤必須是在sql查詢中傳遞變量“ now”時出現的。 如果列Img_date是日期時間字段,則必須將值作為日期時間而不是字符串傳遞。 嘗試將值Datetime.Now分配給參數@date

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

使用DateTime2列時,您需要專門設置參數類型-默認為帶有AddWithValue DateTime

嘗試這個:

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

根據MSDN:

@date參數可以映射到服務器上的date,datetime或datetime2數據類型。 使用新的datetime數據類型時,必須將參數的SqlDbType屬性顯式設置為實例的數據類型。 使用Variant或隱式提供參數值可能會導致與datetime和smalldatetime數據類型向后兼容的問題。

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

希望這可以幫助。

因為tsql不會接受'tt'格式說明符,所以出現了該錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM