Insert, select and update DateTime

后端 未结 2 1203
醉酒成梦
醉酒成梦 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
    }
    
    0 讨论(0)
  • 2021-01-22 20:43

    You should NEVER concatenate together your SQL commands like you do! This opens them up to SQL injection attacks.

    Instead - use parameters! This also gets rid of a lot of conversion issues.

    So in your case, you should use:

    string comando = "INSERT INTO example (date) VALUES (@DateParam)";
    

    and then you need to set the @DateParam on your SqlCommand:

    cmd.Parameters.Add("@DateParam", SqlDbType.Date).Value = YourDataValueHere
    

    and that should take care of all your issues!

    If you want to select - again, use parameters!

    select * 
    from example 
    where date >= @fromDate and date <= @toDate
    

    when you run this from C#.

    If you use T-SQL directly (in Mgmt Studio), then use the ISO-8601 format YYYYMMDD which is indepdent of any dateformat and/or language settings -

    select * 
    from example 
    where date >= '20141025' and date <= '20141028'
    

    This works on any version of SQL Server and with any dateformat, language and regional settinsg.

    0 讨论(0)
提交回复
热议问题