开发者

find highest number in MS access database using C#

开发者 https://www.devze.com 2023-03-21 02:35 出处:网络
How to find the largest number in a particular column of MS access table? I\'m using C#. I\'m not able to make the logic for this. I was doing this:

How to find the largest number in a particular column of MS access table? I'm using 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 fusse开发者_高级运维d !!!!


Barring an obvious reason why not, you should use SQL: SELECT MAX(id) FROM . . ..

You can do this with an OLEDB connection:

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#.


you can use SQL for this purpose

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;


 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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号