如何在C#中存储日期数据类型 [英] How to store the date data type in sql from C#
本文介绍了如何在C#中存储日期数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
My SQL Table格式
My SQL Table format
Crnt_Date -- date
Enter_Date -- date
Time_ -- varchar(10)
Name_ -- varchar(50)
Product_ -- varchar(50)
Count_ -- int
Amount_ -- int
显示当前日期>
DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
int day = dt.Day;
int mon = dt.Month;
int year = dt.Year;
label4.Text = System.Convert.ToString(day + "/" + mon + "/" + year);
要插入我使用的值
To insert the values i use
cn.Open();
cmd = new SqlCommand("insert into Entry(Crnt_Date,Enter_Date,Time_,Name_,Product_,Count_,Amount_)
values('" + Convert.ToDateTime(label4.Text)
+ "','" + Convert.ToDateTime(dateTimePicker1.Text)
+ "','" + comboBox3.Text
+ "','" + lblName.Text
+ "','" + comboBox1.Text
+ "','" + comboBox2.Text
+ "','" + textBox1.Text + "')", cn);
cmd.ExecuteNonQuery();
MessageBox.Show("Inserted");
cn.Close();
但它显示错误消息
字符串未被识别为有效日期时间。
如何将当前日期和日期时间戳日期存储到数据库中?帮助我..
But it show the error message
"String was not recognized as a valid DateTime."
How can i store the current date and datetimepicker date into the db? Help me..
推荐答案
你不想这样做,你将使用命令参数和参数化的sql查询代替(否则你打开您的应用程序最多 SQL注入 [ ^ ](这是坏)。
类似这可能会指向正确的方向;
You don't want to do it that way, you'll ant to use command parameters and a parameterized sql query instead (otherwise you open your application up to SQL Injection[^] (and that is bad).
Something like this might point you in the right direction;
// To display current date
DateTime dt = DateTime.Today;
label4.Text = dt.ToString("dd/MM/yyyy");
// To insert the values
cn.Open();
using (var cmd = new SqlCommand("insert into Entry(Crnt_Date, Enter_Date, Time_,Name_, Product_, Count_,Amount_) values (@Crnt_Date, @Enter_Date, @Time_,Name_, @Product_, @Count_, @Amount_)"), cn)
{
cmd.Parameters.AddWithValue("Crnt_Date", DateTime.ParseExact(label4.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture));
cmd.Parameters.AddWithValue("Enter_Date", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("Time_", comboBox3.Text);
cmd.Parameters.AddWithValue("Name_", lblName.Text);
cmd.Parameters.AddWithValue("Product_", comboBox1.Text);
cmd.Parameters.AddWithValue("Count_", comboBox2.Text);
cmd.Parameters.AddWithValue("Amount_", textBox1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Inserted");
}
cn.Close();
处理可能输入错误的日期文本框查看 DateTime.TryParseExact
。
希望这会有所帮助,
Fredrik
To handle possible incorrectly typed dates in the text boxes look into DateTime.TryParseExact
.
Hope this helps,
Fredrik
您好Vijaydhas,
请试用此代码
Hi Vijaydhas,
Please try this code
cmd = new MySqlCommand("insert into Entry(Crnt_Date,Enter_Date,Time_,Name_,Product_,Count_,Amount_) values('" + DateTime.Now + "','" + Convert.ToDateTime(dateTimePicker1.Text)
+ "','" + comboBox3.Text
+ "','" + lblName.Text
+ "','" + comboBox1.Text
+ "','" + comboBox2.Text
+ "','" + textBox1.Text + "')", cn);
这篇关于如何在C#中存储日期数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文