How to connect Dot Net Visual studio to SQL Server database

Below are the ways to connect your local sql server with visual studio. You can connect sql server for web application or WCF forms.

  1. Create a or open a existing project in visual studio.
  2. Go to controller class and create your connection string

Check SQL Server credentials properly

Connection String for Sql Server

Write following code in Controller Class

public string dataconn()
{
SqlConnectionStringBuilder csb = new SqlConnectionStringBuilder();
csb.DataSource = “servername”;
csb.InitialCatalog = “master”; database name
csb.IntegratedSecurity = true;

csb.UserID = “sa”;
csb.Password = “”;

        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = csb.ToString();
        
        try
        {
            conn.Open();
            Console.WriteLine("Successfully connected to Sql Server Database as " + csb.UserID);
            Console.WriteLine();

            return "Successfully connected to Sql Server Database as " + csb.UserID;

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return conn.ConnectionString + "Error connected to Sql Server Database as " + ex.Message;
        }
        {

Save and Run the application , Connection will be established and you will get below message

Successfully connected to SQl Server Database as sa

Note:sa is my database username

Leave a Reply

Your email address will not be published. Required fields are marked *