zoukankan      html  css  js  c++  java
  • 操作数据库日期字段

    (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());

  • 相关阅读:
    【网络】【交换机】相关字符串处理
    python【telnet】使用
    【?】使用汇总
    【dbm】【功率】换算
    快速【kill进程】
    常用功能【时间log】
    python切换镜像源
    git报remote HTTP Basic Access denied错误的解决方法
    求取1到n的素数的数学思想——埃拉托斯特尼筛法
    MySQL count(*) 和 count(字段) 区别
  • 原文地址:https://www.cnblogs.com/zhouhb/p/2033932.html
Copyright © 2011-2022 走看看