When working with databases, one of the most common tasks is inserting a new record into a table. This can be done using various methods, but in this article, we will focus on using a SqlCommand in C# to insert a record and also return the new ID.
To begin, let's first understand what a SqlCommand is. It is a class in the System.Data.SqlClient namespace that represents a SQL statement or stored procedure to execute against a database. It allows us to pass in parameters, execute the command, and retrieve any returned data.
Now, let's assume we have a database table called "Users" with the following structure:
| Column Name | Data Type |
|-------------|-----------|
| ID | int |
| Name | varchar |
| Age | int |
| Gender | varchar |
Our goal is to insert a new record into this table and also retrieve the newly generated ID. To do this, we will follow these steps:
1. Create a SqlConnection object to connect to the database.
2. Define our SQL query with a placeholder for the parameters.
3. Create a SqlCommand object and pass in the SQL query and the SqlConnection object.
4. Add the necessary parameters to the SqlCommand object.
5. Execute the command using the ExecuteScalar method, which returns the first column of the first row in the result set.
6. Convert the returned value to an int to get the new ID.
Let's see this in action with a code example:
```
// Step 1: Create a SqlConnection object
SqlConnection connection = new SqlConnection("connectionString");
// Step 2: Define our SQL query
string query = "INSERT INTO Users (Name, Age, Gender) VALUES (@Name, @Age, @Gender); SELECT SCOPE_IDENTITY()";
// Step 3: Create a SqlCommand object
SqlCommand command = new SqlCommand(query, connection);
// Step 4: Add parameters to the command
command.Parameters.AddWithValue("@Name", "John");
command.Parameters.AddWithValue("@Age", 30);
command.Parameters.AddWithValue("@Gender", "Male");
// Step 5: Execute the command and retrieve the new ID
int newID = Convert.ToInt32(command.ExecuteScalar());
// Step 6: Use the newID as needed
Console.WriteLine("New user added with ID: " + newID);
```
In this example, we are using the ExecuteScalar method to return the newly generated ID from the database. This method is useful when we only need to retrieve a single value from the database.
It is important to note that the SCOPE_IDENTITY() function is used to return the last ID inserted into the identity column of a table. This is why we are using it in our SQL query to retrieve the new ID.
Now, let's say we want to insert multiple records into our table at once. In that case, we can use the ExecuteNonQuery method instead of ExecuteScalar. This method is used for executing SQL statements that do not return any data, such as INSERT, UPDATE, or DELETE statements.
```
// Define SQL query for inserting multiple records
string query = "INSERT INTO Users (Name, Age, Gender) VALUES (@Name1, @Age1, @Gender1), (@Name2, @Age2, @Gender2)";