SQLite 日期操作

在数据库中经常会遇到对日期的操作,如插入时期、查询介于某两个日期之间的记录等等,这里记录一个在SQLite中处理时间的例子。由于用到了dotnetBar控件,所以顺带把dotnetBar中的DateTimeInput控件时间格式设置介绍一下。

首先是SQLite中日期的操作

在SQLite中,日期的存储类型为date,下面这个例子,在创建tbIncome表时,创建了一个date类型的列recordDate:

create table if not exists tbIncome  ( 

    id             integer     primary key     autoincrement,

    recordDate     date, 

    amount         float,

    summery     vchar(140)

);

相应地,向tbIncome中插入数据时,对应于recordDate列的应该是一个date类型的日期数据:

insert into tbIncome ( recordDate, amount, summery) values (date('2012-01-01'),1000,"no summery");

如果是从gui的控件获得数据,然后再插入数据库,可以这么写:

  private void btnAddRecord_Click(object sender, EventArgs e)

        {

            var item = new RecordItem();



            item.recordDate = this.dateTimeInput1.Text.Trim();

            item.amount  = (float)Convert.ToDouble( this.tbAmount.Text );

            item.summery = this.tbSummery.Text.Trim();

            
       Insert2Income(item);
DialogResult = DialogResult.Yes; }
 private void Insert2Income(RecordItem i)

        {

            con.Open();

            string sql = string.Format("insert into tbIncome ( recordDate, amount, summery) values (date('{0}'),{1},'{2}')",

                i.recordDate,i.amount,i.summery);

            cmd = new SQLiteCommand(sql, con);

            int n = cmd.ExecuteNonQuery();



            MessageBox.Show(n.ToString()+"records inserted!");

            con.Close();

            

        }

SQlite中默认的日期格式时4位年,2位月,2位日,也就是yyyy-MM-dd格式,在插入日期数据时,不论我们给出的时2012-01-01还是2012-1-1,插入到数据库之后都是2012-01-01,因此在后续我们要对数据库中的日期进行操作时,都必须用yyyy-MM-dd格式,否则肯定什么也查不到:

select * from tbIncome where recordDate between '2012-02-02' and '2012-05-05'

好了,下一个话题。在实际的应用中,我们一般会在gui上有一日期选择的控件,让用户选一个查询的起始日期或终止日期之类,在标准的winform中一般式DateTimepicker,这里我用得是DotnetBar里的DateTimeinput,和DateTimepicker类似。

DateTimeInput默认的日期格式是short型,也就是yyyy-mm-dd格式,直接用这个去查数据库是不行的,因此我们在控件的初始化时修改他的日期格式:

this.dateTimeInput1.CustomFormat = "yyyy-MM-dd";

this.dateTimeInput1.Format = DevComponents.Editors.eDateTimePickerFormat.Custom;

在查询数据库时,使用类似下面的语句:

string sql = string.Format("select * from tbIncome where recordDate between '{0}' and '{1}'", this.dateTimeInput1.Text.Trim(),this.dateTimeInput2.Text.Trim());

 

你可能感兴趣的:(sqlite)