How to connect to a database in C# WebAPI?

In C# WebAPI, you can use ADO.NET to connect to the database. ADO.NET is a framework for accessing databases, offering a range of classes and methods for connecting to and manipulating the database.

Here is an example of connecting to a database using ADO.NET:

  1. Firstly, you need to add a reference to the database provider in your project. For example, if you are connecting to a SQL Server database, you need to add a reference to System.Data.SqlClient.
  2. Create a database connection string that specifies the address of the database server, the database name, the username, and password, etc. For example:
string connectionString = "Data Source=serverName;Initial Catalog=databaseName;User ID=userName;Password=password";
  1. Connection to a SQL database
SqlConnection connection = new SqlConnection(connectionString);
  1. Open the database connection.
connection.Open();
  1. Performing database operations, such as executing SQL queries, inserts, updates, and so on. Here is an example of executing a query:
string query = "SELECT * FROM TableName";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    // 读取查询结果
}

reader.Close();
  1. Close the database connection.
connection.Close();

The above is a basic example of connecting to and querying a database, which you can expand and modify according to your needs. Please note that in actual development, in order to prevent SQL injection attacks, you should use parameterized queries instead of directly concatenating SQL statements.

Additionally, there are other ORM (Object-Relational Mapping) tools available that can simplify database access, such as Entity Framework, Dapper, etc. You can choose the most suitable tool based on your preferences and project requirements.

bannerAds