我的数据库中有一列内容如下:
status
2018-12-31 15:31:56.000 (result of a select in SMSS)
我正在尝试通过 C# 中的查询在 ASP.NET 页后的代码中获取此列的数据:
var connectionString = System.Configuration.ConfigurationManager.AppSettings["connection"];
SqlConnection con = new SqlConnection(connectionString);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 [status] from [tablename] where idNo = '" + idNo+ "'", con);
con.Open();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Debug.WriteLine("n Rows extracted."); // -> Error thrown here.
Debug.WriteLine("n Rows content:" + DateTime.ParseExact(dt.Rows[0][0].ToString(), "yyyy-MM-dd hh:mm:ss.000", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None));
con.Close();
da.Dispose();
}
无论我尝试什么,我总是得到
字符串未被识别为有效的日期时间
或者日期时间未被识别为公历的一部分。
我尝试直接显示dt.Rows[0][0]
内容,但随后出现有关日期不在公历中的错误。
我可以采取任何步骤来了解这是怎么回事?
在 C# 中使用 DateTime
绝对是一场噩梦,我希望 MS 最终能解决这个问题。
请不要将我指向文档或其他文章,这显然是我来自的地方......
格式字符串方面,大小写很重要。请参阅:https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
您实际想要的字符串是:
yyyy-MM-dd HH:mm:ss.fff
请注意月、小时和分钟的情况。
h = 12 小时制,H = 24 小时制。
演示
现在,您只需要采用调用数据库的最佳实践。使用参数化查询并阅读使用语句
您应该使用MM
(大写(,表示月份,mm
(小写(为分钟。
if (dt.Rows.Count > 0)
{
Debug.WriteLine("n Rows extracted."); // -> Error thrown here.
Debug.WriteLine("n Rows content:" + DateTime.ParseExact(dt.Rows[0][0].ToString(), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None));
con.Close();
da.Dispose();
}
注意:请不要在查询中连接数据,这将是对黑客进行SQL注入的邀请。改用参数化查询
更多信息 : https://stackoverflow.com/a/7505842/2131576