C# 使用C查找MS access数据库中的最大数字
如何在MS access表的特定列中查找最大数?我用的是C 我无法解释这其中的逻辑。我是这样做的:C# 使用C查找MS access数据库中的最大数字,c#,ms-access,C#,Ms Access,如何在MS access表的特定列中查找最大数?我用的是C 我无法解释这其中的逻辑。我是这样做的: 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 (
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();
}
}
我很紧张 除非有明显的原因,否则应该使用SQL:SELECT MAXid FROM 您可以通过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();
请注意,我在Linux机器上,所以我没有测试上述内容,但它应该与我记忆中的C非常接近。您可以使用SQL来实现此目的
select max(id) from tablename
建议在查询中而不是在代码中执行此操作 问题可能是
Select Max(ColName) From TableName;
您不能从…中选择maxid有什么原因吗?老实说,我没有意识到这个命令,正在尝试使用select*from tablemane。。。。。。有没有链接可以帮助我了解更多关于这些命令的信息?我诚挚的祝贺,我忘了提到我正在使用MS Access数据库Oledb连接类型。我不能简单地键入>>>empilabel.Text=从中选择maxidemp@gsvirdi-我已编辑以演示如何使用OLEDB连接执行此操作。@gsvirdi-还请注意,我可能不会像上面的插图中那样只内联SQL。Thx JasonFruit可供您帮助。我能够理解代码OleDbConnection con=新的OleDbConnection con;var empcon=new oledbcommand从[emp]中选择maxid,con;试试{con.Open;int32max=Int32empcon.ExecuteScalar;empIdLabel.Text=max+1.ToString;}@gsvirdi-听起来你已经知道了。祝你好运哦,对不起。。。我误解了。。。。但现在的问题是如何将数值输入到代码中?。empilabel.Text=??????
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();