Search code examples
c#sqlconnection

C# - How can I do MS SQL Server Connection?


I started programming recently and at the moment I am developing a program with SQL Server 2019 and Visual Studio 2019 in C# that performs simple functions for inserting, deleting and displaying data but I cannot understand how to set up the initial connection with SQL Server. I already connected the Database from Tools->Connect to Database... and the connection test was successful, but now I don't know how to set the connection via SQL Server Authentication by code.


Solution

  • It all depends how you want create the connection really..

    At the very top of your form be sure to include

    using System.Data.SqlClient;
    using System.Configuration;
    

    Depending on how you want to create the connection on whatever button trigger or page load... this scenario would be for you to get specific fields of a query:

    string qString = "SELECT value1,value2,value3 FROM database WHERE value 1 = 'hello world'";
    
    using(SqlConnection connection0 = new SqlConnection(ConfigurationManager.ConnectionStrings["CONNECTION_STRING_NAME_HERE"].ToString()))
    using(SqlCommand command0 = connection0.CreateCommand())
    {
        command0.CommandText = qString;
    
        connection0.Open();
    
        using (SqlDataReader reader = command0.ExecuteReader())
        {
            while (reader.Read())
            {
                value1string = reader["value1"].ToString();
                value2string = reader["value2"].ToString();
                value3string = reader["value3"].ToString();
            }
        }
    
        connection0.Close();
    }
    

    Be sure to add the connection string to the app.config file:

    <connectionStrings>
        <add name="CONNECTION_STRING_NAME_HERE" 
             connectionString="Data Source=SERVERINSTANCENAME;Initial Catalog=YOUR_DATABASE_NAME;User ID=DATABASE_USERNAME;Password=DATABASE_USER_PASSWORD;" />
    </connectionStrings>