Hey there, fellow developer! Ready to dive into the world of SQL Server integration with C#? You're in the right place. We're going to walk through building a robust API that talks to SQL Server, using the mighty Microsoft.Data.SqlClient package. Buckle up!
First things first, let's get our project off the ground:
Fire up Visual Studio and create a new C# project.
Now, let's grab that SqlClient package. In your Package Manager Console, run:
Install-Package Microsoft.Data.SqlClient
Easy peasy, right? You're all set to start coding!
Alright, let's get connected to our database. Here's the secret sauce:
string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // Your database magic goes here }
Pro tip: Keep that connection string safe! Consider using configuration files or environment variables.
Time to make your database do some work:
string query = "SELECT * FROM Users WHERE Id = @UserId"; using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@UserId", 1); using (SqlDataReader reader = command.ExecuteReader()) { // Process your results here } }
See how we used a parameterized query? That's your shield against SQL injection. Always use it!
Let's process those results:
while (reader.Read()) { string name = reader["Name"].ToString(); int age = Convert.ToInt32(reader["Age"]); // Do something cool with this data }
CRUD - the bread and butter of database operations. Here's a quick rundown:
string insertQuery = "INSERT INTO Users (Name, Age) VALUES (@Name, @Age)"; using (SqlCommand command = new SqlCommand(insertQuery, connection)) { command.Parameters.AddWithValue("@Name", "John Doe"); command.Parameters.AddWithValue("@Age", 30); int rowsAffected = command.ExecuteNonQuery(); }
We've covered this earlier, but here's a refresher:
string selectQuery = "SELECT * FROM Users"; using (SqlCommand command = new SqlCommand(selectQuery, connection)) using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // Process each row } }
string updateQuery = "UPDATE Users SET Age = @Age WHERE Name = @Name"; using (SqlCommand command = new SqlCommand(updateQuery, connection)) { command.Parameters.AddWithValue("@Age", 31); command.Parameters.AddWithValue("@Name", "John Doe"); int rowsAffected = command.ExecuteNonQuery(); }
string deleteQuery = "DELETE FROM Users WHERE Name = @Name"; using (SqlCommand command = new SqlCommand(deleteQuery, connection)) { command.Parameters.AddWithValue("@Name", "John Doe"); int rowsAffected = command.ExecuteNonQuery(); }
Stored procedures can be your best friends. Here's how to use them:
using (SqlCommand command = new SqlCommand("GetUserByID", connection)) { command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@UserID", 1); SqlParameter outputParam = new SqlParameter("@UserName", SqlDbType.NVarChar, 50); outputParam.Direction = ParameterDirection.Output; command.Parameters.Add(outputParam); command.ExecuteNonQuery(); string userName = outputParam.Value.ToString(); }
Always wrap your database operations in try-catch blocks:
try { // Your database operations here } catch (SqlException ex) { // Log the error, notify someone, the works! } finally { connection.Close(); // Always close your connections! }
Better yet, use using
statements to automatically dispose of your resources.
Now, let's wrap all this goodness in an API. Here's a simple example using ASP.NET Core:
[ApiController] [Route("[controller]")] public class UsersController : ControllerBase { [HttpGet("{id}")] public IActionResult GetUser(int id) { // Use your database logic here to fetch the user // Return Ok(user) if found, NotFound() otherwise } // Implement other CRUD operations similarly }
Don't forget to test! Here's a quick unit test example:
[Fact] public void TestGetUser() { // Arrange var controller = new UsersController(); // Act var result = controller.GetUser(1); // Assert Assert.IsType<OkObjectResult>(result); // Add more assertions as needed }
Want to squeeze out more performance? Try these:
public async Task<IActionResult> GetUserAsync(int id) { using (SqlConnection connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); // Perform async database operations } }
And there you have it! You've just built a solid SQL Server API integration in C#. Remember, practice makes perfect, so keep coding and exploring. The world of data is your oyster!
Need more? Check out the official Microsoft.Data.SqlClient documentation for a deeper dive.
Now go forth and build amazing things! 🚀