使用 SqlDataReader C# 的 MAX(id)
如何更改此设置:
using (SqlCommand myCommand = myConnection.CreateCommand())
{
myConnection.Open();
myCommand.CommandText = "SELECT FormID FROM tbl_Form";
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
int FormID = reader.GetInt32(reader.GetOrdinal("FormID"));
MessageBox.Show(FormID.ToString());
}
}
}
获取 MAX(FormID) ?
我的自然倾向是在 FormID 周围抛出 MAX,但我收到了 IndexOutOfRange 异常。
How do I change this:
using (SqlCommand myCommand = myConnection.CreateCommand())
{
myConnection.Open();
myCommand.CommandText = "SELECT FormID FROM tbl_Form";
using (SqlDataReader reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
int FormID = reader.GetInt32(reader.GetOrdinal("FormID"));
MessageBox.Show(FormID.ToString());
}
}
}
to get MAX(FormID) ?
My natural tendency is to throw a MAX around FormID but I'm getting an IndexOutOfRange exception.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您选择最大 ID 时,不应使用
SqlDataReader
- 查询仅返回一项,默认情况下该项目未命名,因此您现有的查询会中断,因为它需要一个名为“FormID”的结果 - 尽管您可以通过使用“SELECT MAX(FormID) as FormId FROM tbl_Form”
来“修复”您的查询。而是使用ExecuteScalar()
:When you select the maximum id you shouldn't use a
SqlDataReader
- the query returns just one item, which by default is unnamed so your existing query breaks because it expects a result named "FormID" - although you could have "fixed" your query by using"SELECT MAX(FormID) as FormId FROM tbl_Form"
. Instead useExecuteScalar()
:我已经有一段时间没有使用这种数据库访问方式了,但我认为您只需要
调用 ExecuteScalar
It's been a while since I used this style of database access, but I think you just need
along with a call to ExecuteScalar