Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server and C#: get last inserted id

Tags:

c#

sql-server

public static void CreateSocialGroup(string FBUID)
{
    string query = "INSERT INTO SocialGroup (created_by_fbuid) VALUES (@FBUID); SELECT @@IDENTITY AS LastID";

    using (SqlConnection connection = new SqlConnection(ConnectionString))
    {
        SqlCommand command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@FBUID", FBUID);

        connection.Open();
        command.ExecuteNonQuery();
    }
}

Is this the right way to do it? And how do i get LastID in to a variable? Thanks

like image 405
Johan Avatar asked May 24 '11 11:05

Johan


People also ask

Can SQL be used with C?

You can code SQL statements in a C or C++ program wherever you can use executable statements. Each SQL statement in a C or C++ program must begin with EXEC SQL and end with a semicolon (;). The EXEC and SQL keywords must appear on one line, but the remainder of the statement can appear on subsequent lines.

Is SQL and C same?

C is about performing actions. SQL is about storing data, and manipulating data. The only "actions" it is good at are pulling and changing data. Think of all your data like a Venn diagram- SQL lets you "look" at any part of that diagram you want.

Can we connect C with database?

You can then add a new C source file and replace it with this content. Using the ODBC APIs SQLAllocHandle, SQLSetConnectAttr, and SQLDriverConnect, you should be able to initialize and establish a connection to your database.

Which database is best for C?

MYSQL has a pretty good and easy interface to be used with c. You can write basic operations in 30-40 lines of c code.


2 Answers

OUTPUT clause?

string query = "INSERT INTO SocialGroup (created_by_fbuid) 
                OUTPUT INSERTED.IDCol  --use real column here
                VALUES (@FBUID)";
...
int lastId = (int)command.ExecuteScalar();
like image 115
gbn Avatar answered Sep 30 '22 20:09

gbn


You can use ExecuteScalar to get the last value from a Sqlcommand.

The scope_identity() function is safer than @@identity.

like image 36
faester Avatar answered Sep 30 '22 18:09

faester