在数据库中使用多个插入行自动递增日期+ 1天
问题描述:
我完全是C#的新手,我目前使用VS 2013和访问数据库,我试图插入多个记录,但我的问题是我想插入日期时间选择器插入的日期的值,它是一天的自动增量..我试着做的代码基于我学到的东西,它有一个小问题在数据库中使用多个插入行自动递增日期+ 1天
在我的数据库中我想使用循环插入10多条记录,在我的努力会发生什么是这样一个
EID date
---------------
10175 10/9/14
10175 10/9/14
10175 10/9/14
10175 10/9/14
10175 10/9/14
10175 10/9/14
10175 10/9/14
10175 10/9/14
10175 10/9/14
10175 10/9/14
我希望发生的事情是这样的:
EID date
----------------
10175 10/9/14
10175 10/10/14
10175 10/11/14
10175 10/12/14
10175 10/13/14
10175 10/14/14
10175 10/15/14
10175 10/16/14
10175 10/17/14
10175 10/18/14
这里是我的代码,顺便说一下我的EID不是主要的,所以我不介意重复
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
int ctr = 0;
int counter;
counter =int.Parse(TimeIntxt.Text);
String counter2;
for (ctr=0; ctr<10;ctr++)
{
counter++;
counter2 = dateTimePicker1.Value.AddDays(1).ToString();
command.CommandText = "insert into EmployeeData (EID,DateIn) values('" + counter + "','" + counter2 + "')";
command.ExecuteNonQuery();
}
MessageBox.Show("Success");
connection.Close();
答
代码counter2 = dateTimePicker1.Value.AddDays(1).ToString();
的该线路应该是counter2 = dateTimePicker1.Value.AddDays(ctr + 1).ToString();
而且 - 而在你的情况下它不是很重要,但最好使用参数化查询而不是通过串联构建命令,这有助于防止SQL注入。
请参阅MSDN以获取有关命令参数以及如何使用它们的参考信息。
+0
谢谢我会记住你的建议 – 2014-10-10 01:35:56
'counter2 = dateTimePicker1.Value.AddDays(ctr + 1).ToString();' – nilobarp 2014-10-09 14:51:50