怎样求出一个数据库中最后一条记录中某个字段的值?(急)

ameng_2002 2002-06-23 08:07:27
加精
用什么方法比较简便一些?
...全文
33 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
JTCY23 2002-08-21
  • 打赏
  • 举报
回复
tag
ameng_2002 2002-06-24
  • 打赏
  • 举报
回复
谢谢saucer(思归)!
saucer 2002-06-24
  • 打赏
  • 举报
回复
it returns only one record,

SqlConnection myConnection = new SqlConnection(myConnectionString);
SqlCommand myCommand = new SqlCommand("select top 1 * from yourtable order by SomeIDOrDateTimeField DESC", myConnection);
myCommand.Connection.Open();
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (myReader.Read())
{
System.Console.WriteLine(myReader["YourField"].ToString());
}

myReader.Close();

or better yet, if you only need that one column, you can use ExecuteScalar(), for example:

SqlConnection conn = new SqlConnection("Server=localhost;Database=pubs;UID=sa;PWD=;");
SqlCommand cmd = new SqlCommand("Select top 1 au_lname from authors order by au_lname desc",conn);
conn.Open();
String s = (String)cmd.ExecuteScalar();
Console.WriteLine(s);
conn.Close();
ameng_2002 2002-06-23
  • 打赏
  • 举报
回复
select top 1 * from yourtable order by SomeIDOrDateTimeField DESC
是反会一个数据集吗?该怎样提取某一个字段的值?
谢谢!
saucer 2002-06-23
  • 打赏
  • 举报
回复
if you are using SQL Server, the simpler way is to use SQL statement like this:
select top 1 * from yourtable order by SomeIDOrDateTimeField DESC

otherwise, if you do
select * from yourtable

and if you are using DataSet, then just get
ds.Rows[ds.Rows.Count-1]["字段"]

if you are using SqlDataReader, then you need to do something like

String s;
while (dr.Read())
s = (String)dr["字段"];

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧