如何从文本数据库插入日期 [英] how to insert a date from textbox to database
本文介绍了如何从文本数据库插入日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮我插在DD-MM-yyyy格式到SQL Server的文本框中输入一个日期。
我的code是如下: -
please help me to insert a date from a text box in dd-mm-yyyy format to sql server. my code is as follows:-
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();
和它抛出一个异常说: -
转换从字符串转换日期和/或时间时失败。
and it is throwing an exception saying:- Conversion failed when converting date and/or time from character string.
推荐答案
您需要根据您的SQL Server酸盐这样你可以解决问题。
You need to convert data according to you sql server formate that way you can resolve issue ..
尝试
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);
请使用Paramerize查询,以避免SQL INJECTION ...使code不易出错PRON
演练:使用参数在Windows窗体中显示数据查询
Make use of Paramerize query to avoid SQL INJECTION...make code less error pron Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query
这篇关于如何从文本数据库插入日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文