我需要将ASP.Net文本框中的日期提取存储到SQL Server 2008 date
列中。
我收到以下异常消息。
从字符串转换日期和/或时间时转换失败。
我的代码是:
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
int n=4;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection(<Connection String>);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string query = "insert into temp values('" + TextBox1.Text + "')";
cn.Open();
cmd = new SqlCommand(query, cn);
cmd.ExecuteNonQuery();
cn.Close();
Response.Write("Record inserted successfully");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
请帮助..
提前致谢
答案 0 :(得分:4)
将您的代码更改为以下内容(假设temp
中的列实际上是DateTime
):
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string query = "insert into temp values(@Value)";
cn.Open();
cmd = new SqlCommand(query, cn);
cmd.Parameters.AddWithValue("@Value", DateTime.Parse(TextBox1.Text));
cmd.ExecuteNonQuery();
cn.Close();
Response.Write("Record inserted successfully");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
您还应该更改逻辑以验证TextBox1.Text
实际上是否为有效日期。
答案 1 :(得分:0)
答案 2 :(得分:0)
您必须进行多项更改
您的代码就像那样
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
int n=4;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection(<Connection String>);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string query = "insert into temp values(@date))";
cn.Open();
cmd = new SqlCommand(query, cn);
cmd.Parameters.AddWithValue("@date",Convert.DateTime(TextBox1.Text));
cmd.ExecuteNonQuery();
cn.Close();
Response.Write("Record inserted successfully");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}