Here's a comprehensive guide on how to insert data into SQL using C#:
1. Basic Setup with ADO.NET
First, add the necessary using directives:
using System.Data; using System.Data.SqlClient; // For .NET Framework // or using Microsoft.Data.SqlClient; // For .NET Core/.NET 5+
2. Connection String
string connectionString = "Server=your_server;Database=your_database;User Id=your_username;Password=your_password;"; // or for Windows Authentication: // string connectionString = "Server=your_server;Database=your_database;Integrated Security=true;";
3. Basic Insert Example
public void InsertUser(string name, string email) { using (SqlConnection connection = new SqlConnection(connectionString)) { string query = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@Name", name); command.Parameters.AddWithValue("@Email", email); connection.Open(); command.ExecuteNonQuery(); } } }
4. Insert with Return Value (Get Inserted ID)
public int InsertUserReturnId(string name, string email) { using (SqlConnection connection = new SqlConnection(connectionString)) { string query = @"INSERT INTO Users (Name, Email) VALUES (@Name, @Email); SELECT SCOPE_IDENTITY();"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@Name", name); command.Parameters.AddWithValue("@Email", email); connection.Open(); int newId = Convert.ToInt32(command.ExecuteScalar()); return newId; } } }
5. Using Entity Framework Core
First, install the EF Core package:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Define your model and context:
public class User { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } } public class AppDbContext : DbContext { public DbSet<User> Users { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(connectionString); } }
Insert using EF Core:
public void InsertUserWithEF(string name, string email) { using (var context = new AppDbContext()) { var user = new User { Name = name, Email = email }; context.Users.Add(user); context.SaveChanges(); Console.WriteLine($"User inserted with ID: {user.Id}"); } }
6. Bulk Insert
public void BulkInsertUsers(List<User> users) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlTransaction transaction = connection.BeginTransaction()) { try { foreach (var user in users) { using (SqlCommand command = new SqlCommand( "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)", connection, transaction)) { command.Parameters.AddWithValue("@Name", user.Name); command.Parameters.AddWithValue("@Email", user.Email); command.ExecuteNonQuery(); } } transaction.Commit(); } catch { transaction.Rollback(); throw; } } } }
7. Using Dapper (Lightweight ORM)
Install Dapper:
dotnet add package Dapper
using Dapper; public void InsertUserWithDapper(string name, string email) { using (SqlConnection connection = new SqlConnection(connectionString)) { var query = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)"; connection.Execute(query, new { Name = name, Email = email }); } }
8. Error Handling
public bool TryInsertUser(string name, string email) { try { using (SqlConnection connection = new SqlConnection(connectionString)) { string query = "INSERT INTO Users (Name, Email) VALUES (@Name, @Email)"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@Name", name); command.Parameters.AddWithValue("@Email", email); connection.Open(); int rowsAffected = command.ExecuteNonQuery(); return rowsAffected > 0; } } } catch (SqlException ex) { Console.WriteLine($"SQL Error: {ex.Message}"); return false; } catch (Exception ex) { Console.WriteLine($"General Error: {ex.Message}"); return false; } }
9. Async Insert
public async Task<int> InsertUserAsync(string name, string email) { using (SqlConnection connection = new SqlConnection(connectionString)) { string query = @"INSERT INTO Users (Name, Email) VALUES (@Name, @Email); SELECT SCOPE_IDENTITY();"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@Name", name); command.Parameters.AddWithValue("@Email", email); await connection.OpenAsync(); var result = await command.ExecuteScalarAsync(); return Convert.ToInt32(result); } } }
Key Points to Remember:
Always use parameterized queries to prevent SQL injection
Use
using
statements for proper resource disposalHandle exceptions appropriately
Validate input data before inserting
Consider using ORMs like Entity Framework for complex applications
Use async methods for better performance in web applications
Choose the approach that best fits your project's requirements and complexity level!
No comments:
Post a Comment