开发者

Using .net Datetime in sql query

I have a DateTime object I want to compare against an sql datetime field in a where clause. I'm currently using:

"where (convert( dateTime, '" & datetimeVariable.ToString & "',103) <= DatetimeField)"

But I believe datetimeVariable.ToString will return a different value depending on the culture where the system is running.

How would you handle this so it is culture independent?

EDIT : I won't be using paramatised sql in this code...

EDIT : following Parmesan's comment to one of the answers looks like the best method may b开发者_Go百科e:

"where (convert( dateTime, '" & datetimeVariable.ToString( "s" ) & "',126) <= DatetimeField)"


Don't use string concatenation, use a parameterised query. Pass in a parameter value of type DateTime. This avoids the formatting issue altogether, improves performance for subsequent queries, and gets around the inherent vulnerabilities (SQL injection) that you lay yourself open to when forming SQL in this way.

"where @dateTime <= DateTimeField"

Then set the parameter @dateTime. If you need more, tell us a bit more about your code - straight ADO.NET, Enterprise Library, something else?


Parameters. Always parameters:

where @someVar <= DatetimeField

and add a parameter called "@someVar" with that value.

Solves (among other issues) problems with i18n / encoding, concatenation / injection and query-plan re-use.


If you want ToString() to always come out regardless of culture then specify a specific culture:

    Dim D = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture)
    '-or-
    Dim D = DateTime.Now.ToString(New System.Globalization.CultureInfo("en-us"))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜