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