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

时间:2022-03-19 08:51:23

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. and the error I am facing is

现在的问题是我从中获取数据的SQL Server列是日期和时间数据类型。而我面临的错误是

Unable to cast object of type 'System.DateTime' to type 'System.String'.

无法将类型为“System.DateTime”的对象强制转换为“System.String”。

1 个解决方案

#1


3  

You need to use GetDateTime and GetTimeSpan methods:

您需要使用GetDateTime和GetTimeSpan方法:

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

#1


3  

You need to use GetDateTime and GetTimeSpan methods:

您需要使用GetDateTime和GetTimeSpan方法:

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