C#winform如何将用户输入的字符串转换为datetime,以便将其插入SQL Server [英] C# winform how to convert a string entered by the user to datetime so it can be inserted to SQL server
问题描述
我的表单中有一个蒙版文本框,用户输入日期为dd / MM / yyyy
然后将此值插入到sql中服务器表。
执行查询时出现以下错误:
Hi,
I have a masked textbox in my form where the user enters the date as dd/MM/yyyy
and then this value is inserted into a sql server table.
I'm getting the following error when the query is executed:
the conversion of a varchar data type to a datetime data type resulted in an out-of-range value
我尝试了很多方法并尝试在线查找类似问题并尝试修复/答案,但我仍然得到错误。
只有当'dd'输入高于12时才会发生错误所以我假设sql server将该值作为MM而不是dd。
以下是我的尝试。
我尝试过:
I have tried many ways and tried to look for similar issues online and tried the fixes/answers but I'm still getting the error.
The error only happens when the 'dd' entered is higher than 12 so i assume that the sql server is taking that value as the MM instead of dd.
Below is what I tried.
What I have tried:
Datetime receivedDate = DateTime.ParseExact(receivedDate.Text, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
插入语句如下:
The insert statement is as follows:
string query = "INSERT INTO dateTbl(recD) VALUES('" + receivedDate + "')"
推荐答案
请勿在查询中使用连接字符串。请改用参数化查询。
如果这不能完全解决您的问题(它应该),那么请尝试将您的日期格式化为yyyy-Mmm-dd
Don't use a concatenated string in your query. Use a parameterised query instead.
If that doesn't completely solve your problem (it should) then try formatting your date as yyyy-Mmm-dd
请参阅 DateTimePicker类(System.Windows.Forms) )| Microsoft Docs [ ^ ]。
这篇关于C#winform如何将用户输入的字符串转换为datetime,以便将其插入SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!