简体   繁体   English

使用 C# 在 MS 访问数据库中查找最大数字

[英]find highest number in MS access database using C#

How to find the largest number in a particular column of MS access table?如何在 MS 访问表的特定列中找到最大的数字? I'm using C#.我正在使用 C#。

I'm not able to make the logic for this.我无法为此制定逻辑。 I was doing this:我正在这样做:

int i, lastID;
int y = 0;
int lastRow = DS.Tables[0].Rows.Count;
for (i = 0; i > -1; i++)
{
    i = Convert.ToInt32(DS.Tables[0].Rows[i]["id"].ToString());
    lastID = (y > i) ? y : i;
    if (i > lastRow)
    {
        lastID++;
        empIdLabel.Text = lastID.ToString();
    }
}

I'm fussed !!!!我气死了!!!!

Barring an obvious reason why not, you should use SQL: SELECT MAX(id) FROM. . .除非有明显的原因,否则您应该使用 SQL: SELECT MAX(id) FROM. . . SELECT MAX(id) FROM. . . . .

You can do this with an OLEDB connection:您可以使用 OLEDB 连接执行此操作:

OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=blahblah.mdb"));
connection.Open();
OleDbCommand maxCommand = new OleDbCommand("SELECT max(id) from TABLENAME", connection);
Int32 max = (Int32)maxCommand.ExecuteScalar();

Note that I'm on a Linux machine, so I haven't tested the above, but it should be pretty close from what I remember of C#.请注意,我使用的是 Linux 机器,所以我没有测试过上述内容,但它应该与我记得的 C# 非常接近。

 String cs = @"Provider=Microsoft.ACE.OLEDB.12.0;Data    
 Source=databasepath\databasename.mdb"; 
 OleDbConnection con = new OleDbConnection(cs);
 con.Open();
 OleDbCommand com = new OleDbCommand("select Max(id) as ID from tablename",
 con);
 com.CommandType = CommandType.Text;
 OleDbDataReader r = com.ExecuteReader();
 r.Read();
 if (r["ID"].ToString() != "")
           {
               temp = int.Parse(r["ID"].ToString()) + 1;
           }
 else
           {
                temp = 1;
           }
 textBox1.Text = temp.ToString();
 r.Close();
 con.Close();

you can use SQL for this purpose您可以为此目的使用 SQL

select max(id) from tablename

It is recomended to do it in query rather than in code.建议在查询中而不是在代码中进行。

The query could be查询可能是

Select Max(ColName) From TableName;

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

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