操作数据库日期字段
时间:2011-05-01 来源:zhouhb
(1)向SQL Server数据库中的日期字段插入值:
string strconn = @"server=.\student;database=test;uid=sa;pwd=123456";
DateTime t;
if(!DateTime.TryParse(textBox3.Text,out t)) //检查日期格式是否正确
{
MessageBox.Show("日期出入有误,请修改");
return;
}
using (SqlConnection conn = new SqlConnection(strconn))
{
string sql = string.Format("insert into student_info(stud_id,stud_name,enter_date) values('{0}','{1}','{2}')", textBox1.Text, textBox2.Text, t);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
由此可知,SQL Server是把日期字段当作字符串类型来处理的。所以只要日期格式正确的话,不用转换,直接用文本框中的值插入数据库中也是可行的。即sql语句可以为:
string sql = string.Format("insert into student_info(stud_id,stud_name,enter_date) values('{0}','{1}','{2}')", textBox1.Text, textBox2.Text, textBox3.Text);
当然这种利用字符串拼接产生sql语句的方法并不推荐!
如果用DateTimePicker控件,sql语句可以为:
string sql = string.Format("insert into student_info(stud_id,stud_name,enter_date) values('{0}','{1}','{2}')", textBox1.Text, textBox2.Text, dateTimePicker1.Value);
查询某个时间段内的记录可以用如下的代码:
using (SqlConnection conn = new SqlConnection(strconn))
{
string sql = string.Format("select * from student_info where enter_date between '{0}' and '{1}'", dateTimePicker2.Value, dateTimePicker3.Value);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
using (SqlDataReader rd = cmd.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(rd);
dataGridView1.DataSource = dt;
}
}
(2)操作Access日期字段:
插入数据的sql语句:
string sql = string.Format("insert into test(name,enterdate) values('{0}',#{1}#)", textBox2.Text, textBox3.Text);
查询某个时间段内的记录可以用如下的sql语句:
string sql = string.Format("select * from test where enterdate between #{0}# and #{1}#", dateTimePicker1.Value.ToShortDateString(), dateTimePicker3.Value.ToShortDateString());