简体   繁体   English

从SQL Server到C#获取日期时间类型数据

[英]Fetch Datetime type data from SQL Server to C#

I am having a problem in fetching data into variable in c# from SQL Server. 我在从SQL Server获取c#中的变量数据时遇到问题。

Here is my code. 这是我的代码。

SqlConnection myCon = new SqlConnection(@"Data Source=BROWN-PC\KAZIM;Initial Catalog=Agency;Integrated Security=True");

string lastlogt;
string lastlogd;

myCon.Open();

SqlCommand cd2 = new SqlCommand(" SELECT TOP 1 * From (select Top 2 * from Agency.dbo.lastlogindt ORDER BY uid DESC) x ORDER BY uid",myCon);

SqlDataReader sdr;
sdr = cd2.ExecuteReader();
while (sdr.Read()) {
    lastlogd = sdr.GetString(2);
    lastlogt = sdr.GetString(3);

}

myCon.Close();
Dates.Text = lastlogd;
timing.Text = lastlogt;

Now the problem is that the columns of SQL Server from which I'm taking data is of date and time datatypes. 现在的问题是我从中获取数据的SQL Server列是datetime数据类型。 and the error I am facing is 而我面临的错误是

Unable to cast object of type 'System.DateTime' to type 'System.String'. 无法将类型为“System.DateTime”的对象强制转换为“System.String”。

You need to use GetDateTime and GetTimeSpan methods: 您需要使用GetDateTimeGetTimeSpan方法:

while (sdr.Read()) 
{
     lastlogd = sdr.GetDateTime(2);
     lastlogt = sdr.GetTimeSpan(3);
}

There are other methods for various data types: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx 还有其他各种数据类型的方法: http//msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM