如何将日期从文本框插入数据库

本文关键字:插入 数据库 文本 日期 | 更新日期: 2023-09-27 18:24:12

请帮助我将日期从dd-mm-yyyy格式的文本框插入到sql server。我的代码如下:-

        int prio = Convert.ToInt32(Priority.Text);
        string stdate = planstart.Text;
        string endate= planend.Text;
        string actst = actualstart.Text;
        string acten = actualend.Text;

            SqlConnection myconnection = new SqlConnection(constring);
            SqlCommand mycommand = new SqlCommand();
            DataSet mydataset = new DataSet();
            SqlDataAdapter mydataadapter = new SqlDataAdapter();
            myconnection.Open();
            mycommand.Connection = myconnection;
            mycommand.CommandText = " insert into project_status.dbo.Project_Status_Report values('" + projectcode.Text + "','" + projectname.Text + "',(select P_Code from project_status.dbo.Project_Type where Project_Type = '" + projecttype.Text + "')," + prio + ",'" + stdate + "','" + endate + "','" + actst + "','" + acten + "','" + currentstatus.Text + "','" + remark.Text + "','no');";
            mycommand.CommandType = CommandType.Text;
            mycommand.ExecuteNonQuery();

它抛出了一个异常:-从字符串转换日期和/或时间时转换失败。

如何将日期从文本框插入数据库

您需要根据sql server格式转换数据,以便解决问题。。

尝试

String UrDate = "27/12/2011"; 
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo(); 
dateInfo.ShortDatePattern = "dd/MM/yyyy"; 
DateTime validDate= Convert.ToDateTime(toDate, dateInfo); 

设置日期字符串格式

// String to DateTime
 String MyString;
 MyString = "1999-09-01 21:34 PM";
 //MyString = "1999-09-01 21:34 p.m.";  //Depends on your regional settings
 DateTime MyDateTime;
 MyDateTime = new DateTime();
 MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
                                      null);

使用参数化查询来避免SQL注入。。。减少代码错误演练:使用参数化查询在Windows窗体中显示数据

请注意,您需要净化该查询以防止SQL注入攻击。考虑使用参数化查询。仔细阅读,这并不是这个答案的范围。

您应该首先创建强类型DateTime对象,然后按照需要插入的方式对其进行格式化。考虑对代码进行以下修改:

string stdate = DateTime.Parse(planstart.Text).ToString();
string endate = DateTime.Parse(planend.Text).ToString();
string actst = DateTime.Parse(actualstart.Text).ToString();
string acten = DateTime.Parse(actualend.Text).ToString();

编辑

我从ToString()中删除了字符串参数,这样您就可以获得SQL Server可用的有效DateTime字符串。

 con.Open();
 string query = "insert_demo";
    /* date  fromat Stored*/
 TextBox2.Text = DateTime.Now.ToLongDateString();
 SqlCommand com = new SqlCommand(query, con);

 com.CommandType = CommandType.StoredProcedure;
 com.Parameters.AddWithValue("@Name", TextBox1.Text.ToString());
 com.Parameters.AddWithValue("@Date", TextBox2.Text.ToString());
 com.ExecuteNonQuery();