📜  c# insert from with bind array - C# (1)

📅  最后修改于: 2023-12-03 15:13:49.133000             🧑  作者: Mango

C# Insert From with Bind Array

In this tutorial, we will learn how to insert data into a SQL Server database from a C# program using bind arrays. Bind arrays allow us to insert multiple records into the database in a single statement, which can greatly improve performance.

Prerequisites

Before we begin, make sure you have the following:

  • Visual Studio (Community or higher)
  • SQL Server Management Studio (SSMS)
Setting up the Database

To follow along with this tutorial, we will need a table in our database to insert data into. Here's the SQL code to create a simple table:

CREATE TABLE [dbo].[Users](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Email] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)
Creating the C# Program

First, let's create a new C# console application in Visual Studio. We will call it "InsertFromBindArray".

Next, we need to add a reference to the System.Data.SqlClient namespace, which will allow us to work with SQL Server.

using System.Data.SqlClient;

Now, let's create a connection string to connect to our SQL Server database. Replace "Server", "Database", "User Id", and "Password" with your own values:

string connectionString = "Data Source=Server;Initial Catalog=Database;User Id=username;Password=password";

We will also need to create an array to hold our data. For simplicity, we will create an array of objects, where each object represents a record to be inserted into the database:

object[] data = new object[] {
    new { Name = "John", Email = "john@example.com" },
    new { Name = "Jane", Email = "jane@example.com" },
    new { Name = "Bob", Email = "bob@example.com" }
};

In this example, we have created an array of three objects, each with a "Name" and "Email" property.

Now, let's create a SQL statement to insert our data. We will use named parameters to bind our data to the statement:

string sql = @"
    INSERT INTO Users (Name, Email) 
    VALUES (@Name1, @Email1), (@Name2, @Email2), (@Name3, @Email3)
";

In this example, we have created a statement that inserts three records into the "Users" table, using named parameters to bind our data.

Next, we will create a SqlCommand object to execute our SQL statement:

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(sql, connection))
{
    // TODO: Bind parameters and execute SQL statement
}

We have wrapped our code in a using statement, which ensures that our SqlCommand object is properly disposed of when we are finished with it.

Now, let's bind our data to our SQL statement using the AddWithValue method:

command.Parameters.AddWithValue("@Name1", data[0].Name);
command.Parameters.AddWithValue("@Email1", data[0].Email);
command.Parameters.AddWithValue("@Name2", data[1].Name);
command.Parameters.AddWithValue("@Email2", data[1].Email);
command.Parameters.AddWithValue("@Name3", data[2].Name);
command.Parameters.AddWithValue("@Email3", data[2].Email);

In this example, we have used the AddWithValue method to bind each property of our objects to the corresponding named parameter in our SQL statement.

Finally, let's execute our SQL statement using the ExecuteNonQuery method:

connection.Open();
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("Rows affected: {0}", rowsAffected);

The ExecuteNonQuery method will execute our SQL statement and return the number of rows affected.

Conclusion

In this tutorial, we have learned how to insert data into a SQL Server database from a C# program using bind arrays. By using bind arrays, we can greatly improve performance by inserting multiple records in a single statement.