我有一个窗口表单,我想从数据库中检索Datetime [英] I have a window form and I want to retrieve Datetime from database

查看:78
本文介绍了我有一个窗口表单,我想从数据库中检索Datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个窗口表格我希望从数据库中检索日期时间,有一个错误specifeid强制转换无效

i have a window form AND i want to retrieve datetime from database, there was an error specifeid cast is not valid

推荐答案

问题是有一个你可能犯错的方法很多!

最明显的一点就是你将数据库中的DateTime值存储在NVARCHAR列而不是DATE或DATETIME列中,然后进行类似这样的事情:

The problem is that there are a huge number of ways that you could have got this wrong!
The most obvious one is that you are storing your DateTime values in your database in a NVARCHAR column instead of a DATE or DATETIME columns, and then doing something like this:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT dateEntered FROM myTable", con))
        {
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                DateTime entered = (DateTime) reader["dateEntered"];
                ...
                }
            }
        }
    }

因为你的数据库列是基于字符串的,所以SqlReader返回一个字符串值,无法强制转换为DateTime - 您必须使用DateTime.Parse或Datetime.TryParse。



但不要。更改数据库以在DateTime字段中存储基于日期的值。它使他们的工作更容易......

Because your DB column is string based, the SqlReader returns a string value, which cannot be cast to a DateTime - you would have to use DateTime.Parse or Datetime.TryParse.

But don't. Change your database to store Date based values in DateTime fields. It makes workign with them a whole lot easier...


这篇关于我有一个窗口表单,我想从数据库中检索Datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆