我如何从C#中的数据库中获取最后一个ID

时间:2019-12-24 13:10:45

标签: sql-server c#-2.0

我尝试使用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();
}

1 个答案:

答案 0 :(得分:3)

MySQL

是:

SELECT LAST_INSERT_ID() AS id FROM studentdetails

而不是

SELECT LAST_INSERT_id FROM studentdetails

这是因为LAST_INSERT_ID是一个函数,而不是列名。这是假设您正在使用MySQL。

SQL Server

如果您使用的是SQL Server,请使用以下命令:

SELECT SCOPE_IDENTITY() AS id FROM studentdetails

请注意,SCOPE_IDENTITY()函数只能在INSERT之后使用,并且仅当插入行的表具有IDENTITY(自动递增)列。