我如何从C#中的数据库中获取最后一个ID
How can i get the last id from the database in C#
我尝试使用 SELECT
查询从数据库中获取最后一个 ID,即 SELECT LAST_INSERT_id FROM studentdetails
但它对我不起作用。
我真的需要帮助!
请问我可以使用什么查询从数据库中获取最后一个 ID?
string me = dtba.ConnectionString();
SqlConnection connection = new SqlConnection(me);
string selectquery = "SELECT LAST_INSERT_id FROM studentdetails";
SqlCommand selectcmd = new SqlCommand(selectquery, connection);
selectcmd.Parameters.AddWithValue("@id", registrationNo.Text);
try
{
connection.Open();
SqlDataReader reader = selectcmd.ExecuteReader();
if (reader.Read())
{
registrationNo.Text = reader["id"].ToString();
}
if (registrationNo.Text == "")
{
MessageBox.Show("SORRY ID HAS NOT BEEN READ");
}
else
{
MessageBox.Show("REGISTRATION NUMBER IS CORRECT");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
MySQL
是:
SELECT LAST_INSERT_ID() AS id FROM studentdetails
而不是
SELECT LAST_INSERT_id FROM studentdetails
这是因为LAST_INSERT_ID
是函数,不是列名。这是假设您使用的是 MySQL.
SQL 服务器
如果您使用的是 SQL 服务器,请使用:
SELECT SCOPE_IDENTITY() AS id FROM studentdetails
请注意,SCOPE_IDENTITY()
函数只能在 INSERT
之后使用,并且只有当您插入行的 table 具有IDENTITY
(自动递增)列。
我尝试使用 SELECT
查询从数据库中获取最后一个 ID,即 SELECT LAST_INSERT_id FROM studentdetails
但它对我不起作用。
我真的需要帮助!
请问我可以使用什么查询从数据库中获取最后一个 ID?
string me = dtba.ConnectionString();
SqlConnection connection = new SqlConnection(me);
string selectquery = "SELECT LAST_INSERT_id FROM studentdetails";
SqlCommand selectcmd = new SqlCommand(selectquery, connection);
selectcmd.Parameters.AddWithValue("@id", registrationNo.Text);
try
{
connection.Open();
SqlDataReader reader = selectcmd.ExecuteReader();
if (reader.Read())
{
registrationNo.Text = reader["id"].ToString();
}
if (registrationNo.Text == "")
{
MessageBox.Show("SORRY ID HAS NOT BEEN READ");
}
else
{
MessageBox.Show("REGISTRATION NUMBER IS CORRECT");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
MySQL
是:
SELECT LAST_INSERT_ID() AS id FROM studentdetails
而不是
SELECT LAST_INSERT_id FROM studentdetails
这是因为LAST_INSERT_ID
是函数,不是列名。这是假设您使用的是 MySQL.
SQL 服务器
如果您使用的是 SQL 服务器,请使用:
SELECT SCOPE_IDENTITY() AS id FROM studentdetails
请注意,SCOPE_IDENTITY()
函数只能在 INSERT
之后使用,并且只有当您插入行的 table 具有IDENTITY
(自动递增)列。