2

我正在开发 c# 项目并使用 winform。

这里的问题是查询以前工作但现在不工作

todaydate是一个datetimePicker设置为短日期格式的列,我的列数据类型是smalldatetime我得到的错误是

 The conversion of a nvarchar data type to a
     smalldatetime data type resulted in an out-of-range value.
    The statement has been terminated.

如果我有两个日期时间选择器,一个用于日期,第二个用于时间,那么我该如何插入?请你指导我

4

3 回答 3

5

AddWithValue determines the datatype of the parameter from the value you pass.

In your case you are passing a string and thus the parameter is passed to the database as a string not as a datetime expected by the database

you should change that line

cmd.Parameters.AddWithValue("@today", todaydate.Value);
于 2013-01-18T14:02:51.813 回答
4

You're currently passing in the text value, which means something else is having to then parse it as a date. Don't do that. Given that you've got a DateTimePicker, you should just use the DateTime value it provides:

cmd.Parameters.AddWithValue("@today", todaydate.Value);

... or create the parameter first with a specific type (SqlDbType.SmallDateTime), then set the value using todaydate.Value. The important point is to avoid the string conversion.

Wherever possible, you should avoid converting values into text. Keep them in their "natural" form (e.g. DateTime in this case) for as much of the time as possible: on input, parse into the natural form, and if you can avoid ever converting to a string, do so!

于 2013-01-18T14:02:53.870 回答
0

I think your time7 column in database is smalldatetime and you tried to assign it a string. I don't suggest it.

Try with Add() method like this;

command.Parameters.Add("@today", SqlDbType.SmallDatetime);
command.Parameters["@today"].Value = todaydate.Value;

or you can use AddWithValue() as also like this;

cmd.Parameters.AddWithValue("@today", todaydate.Value);
于 2013-01-18T14:03:56.837 回答