Insert, select and update DateTime

后端 未结 2 1204
醉酒成梦
醉酒成梦 2021-01-22 20:16

I have a table with time the column named time and the datatype is Date.

In asp.net I want a query to insert the date, and another so select between 2 date.

2条回答
  •  不思量自难忘°
    2021-01-22 20:40

    If the table really is a DATE/DATETIME/DATETIME2/SMALLDATETIME, you'd be better off doing something more like:

    using (SqlCommand cmd = new SqlCommand("INSERT INTO example (date) values (@param)"))
    {
        cmd.Paramters.Add("@param", SqlDbType.Datetime).Value = DateTime.Now;
    
        cmd.ExecuteNonQuery();
    }
    

    Similarly, when you query the table, something more like:

    using (SqlCommand cmd = new SqlCommand("SELECT * FROM example WHERE date BETWEEN @FromDate AND @ToDate"))
    {
        cmd.Paramters.Add("@FromDate", SqlDbType.Datetime).Value = DateTime.Now;
        cmd.Paramters.Add("@ToDate", SqlDbType.Datetime).Value = DateTime.Now; // Of course, you'd probably want to pass through values as parameters to your method
    
        // Fill your dataset/get your SqlDataReader, etc. as preferred
    }
    

提交回复
热议问题