What is the method in C# for connecting a web API to a …

There are multiple ways to connect to a database in C#, and one common method is as follows:

  1. First, you need to add a reference to the database in the project. This can be done by right-clicking on the project in the “Solution Explorer” in Visual Studio, and then selecting “Add” -> “Reference”.
  2. The following code demonstrates how to create a database connection object using the SqlConnection class in C#.
using System.Data.SqlClient;

string connectionString = "Data Source=(local);Initial Catalog=YourDatabase;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
  1. A command for executing SQL statements.
string query = "SELECT * FROM YourTable";
SqlCommand command = new SqlCommand(query, connection);
  1. Open a database connection and execute a query or command, the code is shown below:
connection.Open();
SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    // 处理查询结果
}

reader.Close();
connection.Close();

This is a common method of connecting to a database using SqlConnection and SqlCommand in C#. Of course, there are other ways to connect to a database, such as using frameworks like Entity Framework, Dapper, etc. The specific method you choose depends on your needs and preferences.

bannerAds