-1

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.

st4ticv0id
  • 39
  • 6
  • I can't remember where it his exactly, but if you navigator over to the connection object you made then right click and select "Properties" you should be able to find the `ConnectionString` attribute. – Barns Mar 08 '20 at 00:07
  • I asume you don't want to use Entity Framework... Take a look at https://dapper-tutorial.net/dapper – Peyu Mar 08 '20 at 00:09
  • This might help [Generate or find Connection String from Visual Studio](https://www.c-sharpcorner.com/UploadFile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/) – Barns Mar 08 '20 at 00:10
  • As @barns points out, you need a *connection string*. Once out have one in place, you can open connections – Flydog57 Mar 08 '20 at 00:11
  • You [create a SqlConnection with the connection string](https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.-ctor?view=netframework-4.8#System_Data_SqlClient_SqlConnection__ctor_System_String_) – stuartd Mar 08 '20 at 00:11

1 Answers1

2

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>
Tieson T.
  • 20,774
  • 6
  • 77
  • 92
Keron Tzul
  • 73
  • 4