我的问题是如何获取表中主键的最大值,将其递增+1,然后将该结果放入特定的textbox.Text,以便稍后作为新记录插入数据库。谢谢
答案 0 :(得分:1)
如果数据库包含大量记录,这可能会导致程序运行缓慢,但它对我来说效果很好。
DataTable myDataTable = new DataTable();
/*
Add record from primary key column to datatable
*/
//Add primary key from datatable to List<int>
List<int> primaryKeyList = new List<int>();
foreach (DataRow row in myDataTable.Rows)
{
primaryKeyList.Add(Int32.Parse(row[0].ToString()));
}
int maxKey = primaryKeyList.Max();
primaryKeyList.Clear();
myDataTable.Dispose();
/*
Do whatever you want with maxKey
*/
或
DataTable myDataTable = new DataTable();
/*
Add record from primary key column to datatable
*/
int maxKey = 0;
//Find max key
foreach (DataRow row in myDataTable.Rows)
{
if(Int32.Parse(row[0].ToString()) > maxKey) maxKey = Int32.Parse(row[0].ToString());
}
myDataTable.Dispose();
/*
Do whatever you want with maxKey
*/
答案 1 :(得分:0)
如果您正在使用MySql Wamp。您可以使用此代码。我希望这项工作。
string con = "SERVER=localhost; user id=root; password=; database=dbname";
private void getMaxID()
{
MySqlConnection connect = new MySqlConnection(con);
MySqlCommand cmd = new MySqlCommand("SELECT MAX(ID) as 'aydi' FROM data1");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
MySqlDataReader dr;
try
}
dr = cmd.ExecuteReader();
while(dr.Read())
{
txtID.Text = dr.GetString("aydi");
}
dr.Close();
{
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(connect.State == ConnectionState.Open)
{
connect.Close();
}
}
}