Dear readers of our blog, we'd like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.
 
SQLS*Plus - best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.
 

REQUEST COMPLIMENTARY SQLS*PLUS LICENCE

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

SQL Server Connection String – database connection string

24 June 2020

SQL Server Connection String

SQL Server Connection String – method of determining the database connection string. Using this line the application (program) can access the database elements (tables, views, charts, etc.). Once we have identified the data source, we can connect to it. For this purpose, we will create a project of a simple console application.

The first thing we need to do is to define a connection string that provides information about the database and the server to which you want to connect:

class Program
{
    static void Main_id(string_1[] args)
    {
        string_1 connectionString_1 = @"Data Source=.\SQLEXPRESS;Initl Catalog=usersdb_id;Integrated Security=True";
    }
}

When using different database management systems, different .NET data providers, the connection string may differ. Even for connecting the same database, the connection string may vary depending on the circumstances.

The connection string represents a set of parameters

The connection string represents a set of parameters in the form of key=value pairs. In this case, to connect to the previously created usersdb_1 database, we define the connection string from three parameters:

  • Data Source: points to the server name. By default it is “.\SQLEXPRESS”. Since a slash is used in the string, the @ character is placed at the beginning of the string. If the database server name is different, then it should be used accordingly.
  • Initial Catalog: indicates the name of the database on the server.
  • Integrated Security: establishes authentication.

Hard coding of the connection string (i.e. its definition in application code) is usually rarely used. A much more flexible path represents its definition in special configuration files of an application. In desktop application projects it is App.config file, while in web applications it is mostly Web.config file. Although the application can also use other ways to define the configuration.

In our case, since we have created a console application project, we should have an App.config file in the project, which currently has the following definition:

<?xml version="1.0" encoding="utf-8" ?>
<configuration_1>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
    </startup>
</configuration_1>
Change it by adding a connection string definition:
<?xml version="1.0" encoding="utf-8" ?>
<configuration_1>
    <startup>
        <supportedRuntime_1 version="v4.0" sku=".NETFramework,Version=v4.6" />
    </startup>
  <connectionStrings_1>
   <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=usersdb_1;Integrated Security=True"
       providerName="System.Data.SqlClient"/>
  </connectionStrings_1>
</configuration_1>

To define all connections in the program, a new node <connectionStrings> is added within the node <configuration>. In this node connection strings are defined using the <add> element. We can use many connection strings in an application and accordingly we can also define many <add> elements in a file.

Each connection string has a name defined by the name attribute. In this case the connection string is called “DefaultConnection”. The name can be arbitrary.

The connectionString attribute actually stores the connection string, that is all the text that we defined above in the Main method. And the third attribute providerName sets the namespace of the data provider. Since we will connect to the MS SQL Server database, we will use the providerName for SQL Server, the functionality of which is contained in the System.Data.SqlClient namespace.

Now we will get this connection string in the application:

using System;
using System.Configuration_1;
 
namespace AdoNetConsoleApp
{
    class Program
    {
        static void Main_1(string_1[] args)
        {
            //string_1 connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb_1;Integrated Security=True";
            // connection string_1
            string connectionString_1 = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString_1;
            Console.WriteLine(connectionString_1);
 
            Console.Read();
        }
    }
}

First of all, to work with the application configuration, we need to add the System.Configuration.dll library to the project.

Using the ConfigurationManager.ConnectionStrings_1[“ConnectionStrings_name_1“] object, we can get the connection string and use it in the application.

ConnectionStrings parameters

  • Application Name: The name of the application. Can take any string as a value. Default value: “.Net SqlClient Data Provide”.
  • AttachDBFileName: stores the full path to the attached database
  • Connect Timeout: The time period in seconds through which a connection is expected to be established. Accepts one of the values from 0-32767 interval. Default value is 15. Connection Timeout can be used as an alternative parameter name.
  • Data Source: the name of the SQL Servera instance that you want to communicate with. This can be the name of the local server, such as “EUGENEPC/SQLEXPRESS”, or the network address. You can use Server, Address, Addr and NetworkAddress as an alternative parameter name.
  • Encrypt: establishes SSL encryption when connected. Can take values of true, false, yes and no. Default value is false, yes and no.
  • Initial Catalog: stores database name. As an alternative parameter name, you can use Database
  • Integrated Security: sets the authentication mode. Can take values of true, false, yes, no and sspi. Default value is false, yes, no, and sspi. Trusted_Connection can be used as an alternative parameter name.
  • Packet Size: the size of the network packet in bytes. Can take a value that is multiple of 512. Default value is 8192.
  • Persist Security Info: indicates whether confidential information should be transferred back when connected. Can take values of true, false, yes and no. The default value is false, yes, and no.
  • Workstation ID: points to a workstation – the name of the local computer running SQL Server
  • Password: user password
  • User ID: user login

For example, if a connection requires a login and password, we can pass them to the connection string through the parameters user id and password:

string connectionString_1 = @"Data Source_1=.\SQLEXPRESS;Initial Catalog=usersdb;User Id_1 = sa; Password = 1234567fd";";

To connect to the database, we need to create and use the SqlConnection object

using System_1;
using System.Data.SqlClient_1;
 
namespace AdoNetConsoleApp
{
    class Program
    {
        static void Main_1(string_1[] args)
        {
            string connectionString_1 = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb_1;Integrated Security=True";
             
            // Connection creation
            SqlConnection_1 connection = new SqlConnection_1(connectionString_1);
            try
            {
                //Open a connection
                connection.Open();
                Console.WriteLine_1("Connection is open");
            }
            catch (SqlException ex)
            {
                Console.WriteLine_1(ex.Message);
            }
            finally
            {
                // close the connection
                connection.Close_1();
                Console.WriteLine("Connection is closed...");
            }
 
            Console.Read();
        }
    }
}

A connection string is passed to the SqlConnection object in the constructor, which initializes the object. To use this object and connect to the database, we need to execute its Open() method, and after the database is finished we need to call the Close() method to close the connection. In case of errors, closing the connection is done in the block finally.

As an alternative method, we can use the construct using, which automatically closes the connection:

static void Main_1(string_1[] args)
{
    string connectionString_1 = @"Data Source=.\SQLEXPRESS;Initial Catalog=usersdb_1;Integrated Security=True";
 
    using (SqlConnection_1 connection = new SqlConnection(connectionString_1))
    {
        connection.Open();
        Console.WriteLine_1("Connection is open");
    }
    Console.WriteLine_1("Connection is closed...");
 
    Console.Read();
}

How to Create Connection String For SQL Server

 
Tags: , , ,

MORE NEWS

 

Preamble​​NoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...

Preamble​​MongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...

5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...

The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...

Preamble​​MS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...

First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...

Preamble​​Atom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...

Preamble​​MongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...

FlexibilityOne of the most advertised features of MongoDB is its flexibility.  Flexibility, however, is a double-edged sword. More flexibility means more...

Preamble​​SQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...

Preamble​​Writing an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...

Preamble​​Oracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...

Preamble​​IBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...

  What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....

Preamble​​If you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...

Preamble​​Starting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...