1

我正在尝试将 a 存储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;
        }

    }
4

3 回答 3

3

错误一定是在sql查询中传递变量“now”时。如果该列Img_date是日期时间字段,那么您必须将值作为日期时间而不是字符串传递。尝试将值分配给Datetime.Now参数@date

cmd.Parameters.AddWithValue("@date", DateTime.Now);
于 2013-01-13T02:13:53.877 回答
1

使用DateTime2列时,您需要专门设置参数类型 - 默认为DateTimewith AddWithValue

尝试这个:

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

根据 MSDN:

@date 参数可以映射到服务器上的日期、日期时间或日期时间2 数据类型。使用新的日期时间数据类型时,必须将参数的 SqlDbType 属性显式设置为实例的数据类型。使用 Variant 或隐式提供参数值可能会导致与 datetime 和 smalldatetime 数据类型的向后兼容性问题。

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

希望这可以帮助。

于 2013-01-13T02:10:07.863 回答
0

您收到该错误是因为 tsql 不接受 'tt' 格式说明符。

于 2013-01-13T02:10:16.623 回答