将日期插入sql数据库时出现问题 [英] Problem while inserting date into a sql database

查看:90
本文介绍了将日期插入sql数据库时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,
请任何人纠正错误,我无法将日期从文本框插入到sql数据库中

Hi Friends,
Please anyone rectify the error, i m not able to insert the date from textbox to sql database

protected void btnAdd_Click(object sender, EventArgs e)
       {
           if(cnn.State==ConnectionState.Closed)
           cnn.Open();
           string str=txtDate.Text ;
           DateTime dt;
           dt = DateTime.Parse(str);
           cmd= new SqlCommand("insert into tbl_holiday values('"+str.ToString()+"','"+txtHoliday.Text+"')",cnn);
           cmd.ExecuteNonQuery();
          


       }

推荐答案

首先确保您的列具有正确的数据类型(DateTime)
然后将日期保留为DateTime.在将其发送到数据库之前,无需将其转换为string.

然后使用SqlParameter发送数据.您现在使用的代码容易受到sql注入的攻击!

First of all make sure your column has the right data type (DateTime)
Then keep dates as DateTime. No need to convert it to string before sending it to your database.

Then use a SqlParameter to send data. The code you are using now is vulnerable for sql injections!

protected void btnAdd_Click(object sender, EventArgs e)
{
if(cnn.State==ConnectionState.Closed)
 cnn.Open();

 DateTime dt = DateTime.Parse(txtDate.Text);
 cmd = new SqlCommand("insert into tbl_holiday values(@date, @holyday)",cnn);
 cmd.Parameters.AddWithValue("@date", dt);
 cmd.Parameters.AddWithValue("@holiday", txtHoliday.Text);
 cmd.ExecuteNonQuery();
}



同样,当您像分析日期一样分析日期时,也应该使用TryParse来查看是否确实可以分析用户的输入.



Also when you parse dates like you do, you should use TryParse to see if you actually can parse the input from the user.

string d = txtDate.Text;
DateTime dt;
if(DateTime.TryParse(d, out dt))
{
    // Parse ok..
}
else{
    // Could not parse the date..
}


传递日期时间变量dt而不是str.

pass your date time variable dt instead of str.

protected void btnAdd_Click(object sender, EventArgs e)
       {
           if(cnn.State==ConnectionState.Closed)
           cnn.Open();
           string str=txtDate.Text ;
           DateTime dt;
           dt = DateTime.Parse(str);
           cmd= new SqlCommand("insert into tbl_holiday values('"+dt+"','"+txtHoliday.Text+"')",cnn);
           cmd.ExecuteNonQuery();



       }


正如我看到的代码所示,您正在将文本框值解析为datetime.但是,您不是在解析日期时间,而是在再次插入文本框的字符串值.试试这个:
As I can see your code, you are parsing the textbox value to datetime. But instead of parsed datetime,you are inserting string value of the textbox again. Try this:
protected void btnAdd_Click(object sender, EventArgs e)
{
   if(cnn.State==ConnectionState.Closed)
   cnn.Open();
   string str=txtDate.Text ;
   DateTime dt;
   dt = DateTime.Parse(str);
   cmd= new SqlCommand("insert into tbl_holiday values('"+str.ToString()+"','"+dt+"')",cnn);
   cmd.ExecuteNonQuery();
}




--Amit




--Amit


这篇关于将日期插入sql数据库时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆