Create Operation using SqlClient
The Create operation allows you to insert new records into a database table. This example demonstrates inserting a new employee record using SqlCommand
.
Key Topics
Insert Example
Example
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=MyDatabase;User Id=myUser;Password=myPassword;";
string query = "INSERT INTO Employees (Name, Department) VALUES (@Name, @Department)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", "John Doe");
command.Parameters.AddWithValue("@Department", "IT");
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(rowsAffected + " row(s) inserted.");
}
}
}
Explanation: This example uses SqlCommand
to execute an INSERT
statement with parameters to securely add a new record to the database.
Key Takeaways
- Use
ExecuteNonQuery
forINSERT
,UPDATE
, andDELETE
commands. - Parameters prevent SQL injection and ensure secure queries.