To work with SQL Server in C#, you will need to use the System.Data.SqlClient namespace, which provides classes and interfaces for accessing and querying SQL Server databases.
Here are the basic steps to work with SQL Server in C#:
1. Install the necessary NuGet package:
To work with SQL Server in C#, you will need to install the System.Data.SqlClient package from NuGet. You can install this package using the NuGet Package Manager Console or the NuGet Package Manager in Visual Studio.
2. Establish a connection:
To interact with a SQL Server database, you need to establish a connection using the SqlConnection class. You will need to provide the connection string, which contains information such as the database server name, database name, and credentials (username and password).
“`csharp
string connectionString = “Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;”;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Your code here
}
“`
3. Execute SQL queries:
To execute SQL queries, you can use the SqlCommand class. You will need to specify the SQL query and the SqlConnection object.
“`csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = “SELECT * FROM Customers”;
using (SqlCommand command = new SqlCommand(sql, connection))
{
// Execute the query
using (SqlDataReader reader = command.ExecuteReader())
{
// Read the data returned by the query
while (reader.Read())
{
string customerName = (string)reader[“CustomerName”];
Console.WriteLine(customerName);
}
}
}
}
“`
4. Execute non-query commands:
To execute non-query commands such as INSERT, UPDATE, or DELETE, you can use the ExecuteNonQuery method of the SqlCommand class.
“`csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string sql = “INSERT INTO Customers (CustomerName) VALUES (‘John Doe’)”;
using (SqlCommand command = new SqlCommand(sql, connection))
{
int rowsAffected = command.ExecuteNonQuery();
Console.WriteLine(“Rows affected: ” + rowsAffected);
}
}
“`
These are the basic steps to work with SQL Server in C#. There are many other features and functionalities available for interacting with SQL Server databases, such as parameterized queries, transactions, and stored procedures. You can explore the System.Data.SqlClient namespace and SQL Server documentation for more advanced usage.