0

I want to try to save the result of this query (I want to get the value of the primary key) into a variable in c# of a MDB database but I don't know how I can do it:

SELECT @@identity FROM Table

I've tried this but it doesn't work:

int variable;

    variable = cmd.CommandText("SELECT @@IDENTITY FROM TABLE");

PD: It isn't all the code, I have a problem only with this part.

4
  • 1
    Read about ExecutScalar() Commented May 26, 2015 at 20:44
  • generally speaking, you EXECUTE your query, which returns a statement handle, from which you fetch one or more rows of result data. Commented May 26, 2015 at 20:44
  • What object is cmd? IDbCommand has a CommandText property, but no method by that name. Commented May 26, 2015 at 20:49
  • The ExecuteScalar() works <3 Ty Commented May 26, 2015 at 20:54

2 Answers 2

2

You can use this snippet:

 SqlCommand command = new SqlCommand(
          "SELECT @@IDENTITY FROM TABLE",
          connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                    reader.GetString(1));
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

0

Is it complete code? You just created command object, but didn't open the connection and did not run the command.

using (SqlConnection conn = new SqlConnection(connString))
{
      SqlCommand cmd = new SqlCommand("SELECT @@IDENTITY FROM TABLE", conn);
        try
        {
            conn.Open();
            newID = (int)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.