DotNet / C# Database Connection,How to connect SQL Server?

edited February 2023 in Web Development

Hello guys...

Basically, When we try to access Ms-SQL then have to use the application MsSql Server Management Studio and create a connection and a database to connect with...

To make the connection between the database and Dotnet, We have to configure it in class, and to use it as the same in the total class we can declare that in the IConfiguration function, As shown below.

firstly create a variable to IConfiguration,

public readonly IConfiguration _configuration;

As same as above create a variable for SqlConnection and DataTable;

private SqlConnection con;
private DataTable dt;

After declaring all the variables create a Method or function in which we will create or establish the database connection, As below follows

public UsersController(IConfiguration configuration)
{
            _configuration = configuration;
            con = new SqlConnection(_configuration.GetConnectionString("Database").ToString());
            dt = new DataTable();
} 


By this, we have successfully created a Connection between the Database and Dotnet.

But to access the database we need a query, So to execute the query we need SqlDataAdapter class and after executing we need to assign that result to the data table so that the query effect and gets results of the query as below,

SqlDataAdapter da = new SqlDataAdapter("select * from tablename", con);
da.Fill(dt);

The total process for connection is below:

public readonly IConfiguration _configuration; 
        private SqlConnection con;
        private DataTable dt;
        public UsersController(IConfiguration configuration)
        {
            _configuration = configuration;
            con = new SqlConnection(_configuration.GetConnectionString("Database").ToString());
            dt = new DataTable();
        }
    SqlDataAdapter da = new SqlDataAdapter("select * from mobile_otp", con);
            da.Fill(dt);

Thank you...😇

Sign In or Register to comment.