日期从sql到c# [英] dates from sql to c#

查看:73
本文介绍了日期从sql到c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL中有一个名为OEETable的表,除其他内容外,它还包含RecordIDRecordDate字段.

我正在尝试使用以下代码检索这些字段:

I have a table in SQL called OEETable, it contains amongst other things, RecordID and RecordDate field.

I am trying to retrieve these fields using code below:

//*** Get Record ID ***

SqlCommand readRecID = new SqlCommand();
string sqlReadRecID = "Select max(RecordID) from OEETable";

readRecID.Connection = databaseConnection;
readRecID.CommandText = sqlReadRecID;

SqlDataReader getRecId;

getRecId = readRecID.ExecuteReader();
getRecId.Read();

Int32 recid = getRecId.GetInt32(0);

getRecId.Close();


*** Get Record Date ***

SqlCommand readDate = new SqlCommand();
string sqlReadDate = "Select max(RecordDate) from OEETable";

readDate.Connection = databaseConnection;
readDate.CommandText = sqlReadDate;

SqlDataReader getReadDate;

getReadDate = readDate.ExecuteReader();
getReadDate.Read();

string date = getReadDate.ToString();
getReadDate.Close();


我完全没问题地找到了RecordID,但是获取日期却不走运.

任何帮助将不胜感激.


I retrieve the RecordID absolutely fine, but no luck with getting the date.

Any help would be appreciated.

推荐答案


我读了你的代码.您的错误是在此行中:
Hi,
I read your code. Your mistake is in this line:
string date = getReadDate.ToString();


您需要编写以下代码才能从数据库中获取DateTime值:


You need to write this in order to fetch a DateTime value from the database:

DateTime date = getReadDate.GetDateTime(0);



关键是每种数据类型在SqlDataReader中都有特定的方法.在这里看看这个班级:
http://msdn.microsoft.com/en-us/library/system. data.sqlclient.sqldatareader.aspx [ ^ ]

希望对您有帮助,
干杯.



The point is that every data type has a specific method in SqlDataReader. Take a look at this class here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx[^]

I hope it helps,
Cheers.


而不是通过ExecuteScalar()使用ExecuteReader().它从第一行返回第一个值作为Object.

Instead of using ExecuteReader() using ExecuteScalar(). It returns the first value from the first row as an Object.

Object temp = readDate.ExecuteScalar();



另外,您可能必须在SQL中为该列添加别名,以使其具有名称.



Also, you may have to alias the column in your SQL so that it has a name.

Select max(RecordDate) AS MaxDate from OEETable


感谢瑞安,但是Execute Scalar不会帮我这样做,因为表中的第一列是RecordID,我可以检索到它很好,因为它只是一个整数,所以RecordDate列是表中的第二列.
Thanks Ryan, but Execute Scalar wont do it for me as the first column in my table is RecordID and i can retrieve that just fine as it is just an integer, the RecordDate column is the second column in my table.


这篇关于日期从sql到c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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