Как соединиться с sql сервером
Перейти к содержимому

Как соединиться с sql сервером

  • автор:

Connect to SQL Server Using Management Studio

In this tutorial, let us learn how to connect to SQL Server Using SQL Server Management Studio (SSMS). Using the SQL Server Management Studio is a simple and easy way to connect to the SQL Server Instance.

If you have not installed the SQL Server, then you must visit how to install SQL Server & How to install SQL Server Management Studio tutorials

Table of Contents

Starting SSMS

Start SQL Server Management Studio. You can find it from

Program files -> Microsoft SQL Server Tools 18 -> Microsoft SQL Server Management Studio

SQL Server Management Studio in Program Files

The first time you run SSMS, the Connect to Server window opens.

If it doesn’t open, you can open it manually by selecting Object Explorer > Connect > Database Engine. If Object Explorer is not opened, you can open it from the Menu -> View -> Object Explorer

Object Explorer Menu

Object Explorer

Connect to Server

The Connect to Server window appears as shown below

Server Type: Choose Database Engine to connect to SQL Server database Server.

Server Name: Server Instance Name. Use your computer name if you want to connect to default Instance. Else enter the name as <compuetName>\<InstanceName>

The instance name is the name you have given when you were installing the SQL Server under Instance Configuration.

Authentication: There are two authentication modes. One is Windows & Another one is SQL Server authentication mode. If you choose windows, then the current logged in user is automatically picked by the system.

SQL Server Authentication works only if you have selected the Mixed Mode authentication when you were installing the SQL Server. We set up this while configuring the database engine.

User Name: This is enabled when you choose SQL Server Authentication Mode. If you are connecting to the newly installed SQL Server then the only user you have is sa.

Password: Enter the sa password

Connect to SQL Server Using Windows Authentication

Connect to SQL Server Using SQL Server Authentication

Click on Connect to Connect to the Server

Object Explorer

The SSMS connects to the SQL Server Instance. On Successful connection, you will see the object explorer as shown in the image below.

SQL SERVER Connected Via SQL Server Management Studio

Under the Server Name, you will see various nodes like database, security, management listed. Expand the Databases node to see the list of databases available. In a newly installed server, you won’t see any database except for the System databases.

Summary

We use SSMS to connect to the database. SSMS Provides the GUI tools to explore & Manage a database instance.

How to connect to your local MSSQL server using SSMS?

This post was most recently updated on January 13th, 2023.

Every now and then you run into a situation, where you really need to run some SQL against your local development database. That database, at least in my case, is hosted on your local SQL Server Express.

Connecting to a local SQL Server should be a walk in a park, right? Eh, well…

While using a connection string to connect to said DB is easy, you can’t do that with the SQL Server Management Studio. I wish you could, but hey – it is what it is.

There’s a couple of ways to connect, though! Let’s start with the easy one, that doesn’t always work:

How to connect to your local database with SQL Server Management Studio?

Table of Contents

Connecting to the local instance might work by using the name of the instance. While I’m not sure what’s the reason it hasn’t worked for me (I wonder if the instance names differs based on what you’re installing the SQL Server or SQL Express with. ), maybe it works for you.

Essentially, just paste this into the connection window:

Or like shown below:

How to log in to local SQL Server database using SQL Server Management Studio.

How to log in to local SQL Server database using SQL Server Management Studio.

Workaround: Use Named Pipes instead

If it doesn’t work – well, there’s a workaround, although it’s a bit laborious. It in fact requires you to know the instance name pipe – a weird, nonsensical URI-looking piece of textual vomit you simply can’t guess. And then, most of the time, you can just use your local user account to log in.

The workaround has quite a few steps, and finally comes down to this beautiful screen below:

How to log in to local SQL Server using named pipes.

How to log in to local SQL Server using named pipes.

But how do you figure out the right Server name? Check out the steps below!

Time needed: 10 minutes.

    Try using (localdb)\MSSqlLocalDb first

It won’t hurt testing “(localdb)\MSSqlLocalDb” for Server name – just to see if it works.

The location is something like this under your SQL Server’s installation path -> Tools -> Binn.

Easy enough – run this in your console:
SqlLocalDB.exe

SqlLocalDB.exe output in console.

The tool should output something like this:

Next, let’s run the command with parameter “info”.
> SqlLocalDB info
MSSQLLocalDB
ProjectsV13

Now we’ll get to actually run the command for our instance. This’ll look somewhat like below:
SqlLocalDB info [instancename]

You’ll want to get this server up and running. That’s easy – just run the command below:
SqlLocalDB start MSSQLLocalDB

The output might be something like below:

Or in text form:
SqlLocalDB info MSSQLLocalDB
Name: MSSQLLocalDB
Version: 13.1.4001.0
Shared name:
Owner: [username]
Auto-create: Yes
State: Running
Last start time: 2020-08-12 1:22:49 PM
Instance pipe name: np:.\pipe\LOCALDB#A4E758FA\tsql\query

Pay very close attention to the state – it should now be “running” – and note “Instance pipe name“!

And boom! You should be good.

Frequently asked questions

The executable installation file is hosted by Microsoft – they keep changing the shortlink of the actual download, so your best bet is to download it from the Learn/Docs page describing the tool – here: https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver16

References and appendices

Updated 13.2.2020: Added mention of the easier method, thanks Mika Berglund.

For further reference, check out these links:

Appendix 1: the output of SqlLocalDB.exe

I’m including the whole default output of SqlLocalDB.exe here, as it won’t fit into the step-by-step instructions above.

mm

Antti Koskela is a proud digital native nomadic millennial full stack developer (is that enough funny buzzwords? That’s definitely enough funny buzzwords!), who works as Solutions Architect for Precio Fishbone, building delightful Digital Workplaces.

He’s been a developer from 2004 (starting with PHP and Java), and he’s been working on .NET projects, Azure, Office 365, SharePoint and a lot of other stuff. He’s also Microsoft MVP for Azure.

Как соединиться с sql сервером

Для работы с базой данных MS SQL Server в .NET 5 и выше (а также .NET Core 3.0/3.1) необходимо установить в проект через nuget пакет Microsoft.Data.SqlClient :

Microsoft.Data.SqlClient и подключение к MS SQL Server в .NET Core и в NET 6

Для создания подключения к MS SQL Server применяется класс SqlConnection из пространства имен Microsoft.Data.SqlClient.

Этот класс имеет три конструктора:

Второй и третий конструкторы в качестве первого параметра принимают строку подключения. Третий конструктор также принимает объект SqlCredential , который фактически представляет логин и пароль.

Теперь проверим подключение на примере сервера LocalDB:

В данном случае подключение осуществляется к серверу LocalDB и его базе данных master (по умолчанию база данных master уже должна быть на любом MS SQL Servere).

Для начала взаимодействия с базой данных нам надо открыть подключение с помощью методов Open() (синхронный) или OpenAsync() (асинхронный).

По окончании работы с SqlConnection необходимо закрыть подключение к серверу, вызвав метод Close()/CloseAsync() или Dispose()/DisposeAsync() . В данном случае вначале проверяем, что подключение открыто и, если оно открыто, вызываем асинхронный метод OpenAsync() .

В итоге, если указана валидная строка подключения, то мы должны увидеть на консоли следующие строки:

Вместо явного закрытия подключения также можно использовать конструкцию using , которая автоматически закрывает подключение:

Получение информации о подключении

Объект SqlConnection обладает рядом свойств, которые позволяют получить информацию о подключении:

SQL Server connection strings

Microsoft SqlClient Data Provider for SQL Server

Standard Security

Trusted Connection

Connection to a SQL Server instance

The server/instance name syntax used in the server option is the same for all SQL Server connection strings.

Server = myServerName\myInstanceName; Database = myDataBase; User Id = myUsername; Password = myPassword;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Server = myServerName,myPortNumber; Database = myDataBase; User Id = myUsername; Password = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Connect via an IP address

DBMSSOCN=TCP/IP is how to use TCP/IP instead of Named Pipes. At the end of the Data Source is the port to use. 1433 is the default port for SQL Server. Read more here.

Enable MARS

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

User Instance on local SQL Server Express

The User Instance feature is deprecated with SQL Server 2012, use the SQL Server Express LocalDB feature instead.

LocalDB automatic instance

The first connection to LocalDB will create and start the instance, this takes some time and might cause a connection timeout failure. If this happens, wait a bit and connect again.

LocalDB automatic instance with specific data file

LocalDB named instance

To create a named instance, use the SqlLocalDB.exe program. Example SqlLocalDB.exe create MyInstance and SqlLocalDB.exe start MyInstance

Server = (localdb)\MyInstance; Integrated Security = true;

LocalDB named instance via the named pipes pipe name

The Server=(localdb) syntax is not supported by .NET framework versions before 4.0.2. However the named pipes connection will work to connect pre 4.0.2 applications to LocalDB instances.

Executing SqlLocalDB.exe info MyInstance will get you (along with other info) the instance pipe name such as «np:\\.\pipe\LOCALDB#F365A78E\tsql\query».

LocalDB shared instance

Both automatic and named instances of LocalDB can be shared.

Server = (localdb)\.\MyInstanceShare; Integrated Security = true;

Use SqlLocalDB.exe to share or unshare an instance. For example execute SqlLocalDB.exe share «MyInstance» «MyInstanceShare» to share an instance.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Data Source = myServerAddress; Failover Partner = myMirrorServerAddress; Initial Catalog = myDataBase; Integrated Security = True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Asynchronous processing

A connection to SQL Server that allows for the issuing of async requests through ADO.NET objects.

Server = myServerAddress; Database = myDataBase; Integrated Security = True; Asynchronous Processing = True;

Using an User Instance on a local SQL Server Express instance

The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL Server instance to a user with limited administrative rights on the computer.

Data Source = .\SQLExpress; Integrated Security = true; AttachDbFilename = C:\MyFolder\MyDataFile.mdf; User Instance = true;

To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure ‘user instances enabled’, ‘1’. To disable the functionality execute sp_configure ‘user instances enabled’, ‘0’.

Specifying packet size

By default, the Microsoft .NET Framework Data Provider for SQL Server sets the network packet size to 8192 bytes. This might however not be optimal, try to set this value to 4096 instead. The default value of 8192 might cause Failed to reserve contiguous memory errors as well, read more here.

Always Encrypted

This one is available in .NET Core (as opposed to System.Data.SqlClient).

Always Encrypted with secure enclaves

This one is available in .NET Core (as opposed to System.Data.SqlClient).

.NET Framework Data Provider for SQL Server

Standard Security

Trusted Connection

Connection to a SQL Server instance

The server/instance name syntax used in the server option is the same for all SQL Server connection strings.

Server = myServerName\myInstanceName; Database = myDataBase; User Id = myUsername; Password = myPassword;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Server = myServerName,myPortNumber; Database = myDataBase; User Id = myUsername; Password = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Trusted Connection from a CE device

A Windows CE device is most often not authenticated and logged in to a domain but it is possible to use SSPI or trusted connection and authentication from a CE device using this connection string.

Data Source = myServerAddress; Initial Catalog = myDataBase; Integrated Security = SSPI; User ID = myDomain\myUsername; Password = myPassword;

Note that this will only work on a CE device.

Connect via an IP address

DBMSSOCN=TCP/IP is how to use TCP/IP instead of Named Pipes. At the end of the Data Source is the port to use. 1433 is the default port for SQL Server. Read more here.

Enable MARS

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

User Instance on local SQL Server Express

The User Instance feature is deprecated with SQL Server 2012, use the SQL Server Express LocalDB feature instead.

LocalDB automatic instance

The first connection to LocalDB will create and start the instance, this takes some time and might cause a connection timeout failure. If this happens, wait a bit and connect again.

LocalDB automatic instance with specific data file

LocalDB named instance

To create a named instance, use the SqlLocalDB.exe program. Example SqlLocalDB.exe create MyInstance and SqlLocalDB.exe start MyInstance

Server = (localdb)\MyInstance; Integrated Security = true;

LocalDB named instance via the named pipes pipe name

The Server=(localdb) syntax is not supported by .NET framework versions before 4.0.2. However the named pipes connection will work to connect pre 4.0.2 applications to LocalDB instances.

Executing SqlLocalDB.exe info MyInstance will get you (along with other info) the instance pipe name such as «np:\\.\pipe\LOCALDB#F365A78E\tsql\query».

LocalDB shared instance

Both automatic and named instances of LocalDB can be shared.

Server = (localdb)\.\MyInstanceShare; Integrated Security = true;

Use SqlLocalDB.exe to share or unshare an instance. For example execute SqlLocalDB.exe share «MyInstance» «MyInstanceShare» to share an instance.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Data Source = myServerAddress; Failover Partner = myMirrorServerAddress; Initial Catalog = myDataBase; Integrated Security = True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Asynchronous processing

A connection to SQL Server that allows for the issuing of async requests through ADO.NET objects.

Server = myServerAddress; Database = myDataBase; Integrated Security = True; Asynchronous Processing = True;

Using an User Instance on a local SQL Server Express instance

The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL Server instance to a user with limited administrative rights on the computer.

Data Source = .\SQLExpress; Integrated Security = true; AttachDbFilename = C:\MyFolder\MyDataFile.mdf; User Instance = true;

To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure ‘user instances enabled’, ‘1’. To disable the functionality execute sp_configure ‘user instances enabled’, ‘0’.

Specifying packet size

By default, the Microsoft .NET Framework Data Provider for SQL Server sets the network packet size to 8192 bytes. This might however not be optimal, try to set this value to 4096 instead. The default value of 8192 might cause Failed to reserve contiguous memory errors as well, read more here.

Always Encrypted

Always Encrypted in System.Data.SqlClient is available only for .NET Framework, not .NET Core. To use Always Encrypted in .NET Core switch to Microsoft.Data.SqlClient (NuGet-package).

Always Encrypted with secure enclaves

Always Encrypted in System.Data.SqlClient is available only for .NET Framework, not .NET Core. To use Always Encrypted in .NET Core switch to Microsoft.Data.SqlClient (NuGet-package).

Microsoft OLE DB Driver for SQL Server

Standard security

ADO to map new data types

For ADO to correctly map SQL Server new datatypes, i.e. XML, UDT, varchar(max), nvarchar(max), and varbinary(max), include DataTypeCompatibility=80; in the connection string. If you are not using ADO this is not necessary.

Provider = MSOLEDBSQL; DataTypeCompatibility = 80; Server = myServerAddress; Database = myDataBase; UID = myUsername; PWD = myPassword;

Trusted connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Provider = MSOLEDBSQL; Server = myServerName\theInstanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Provider = MSOLEDBSQL; Server = myServerName,myPortNumber; Database = myDataBase; UID = myUsername; PWD = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Provider = MSOLEDBSQL; Data Source = myServerAddress; Failover Partner = myMirrorServerAddress; Initial Catalog = myDataBase; Integrated Security = True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Availability group and failover cluster

Enable fast failover for Always On Availability Groups and Failover Cluster Instances. TCP is the only supported protocol. Also set an explicit timeout as these scenarios might require more time.

Provider = MSOLEDBSQL; Server = tcp:AvailabilityGroupListenerDnsName,1433; MultiSubnetFailover = Yes; Database = MyDB; Integrated Security = SSPI; Connect Timeout = 30;

MultiSubnetFailover will perform retries in parallell and do it faster than default TCP retransmit intervals. This can not be combined with mirroring, e.g. Failover_Partner=mirrorServer.

Read-Only application intent

Use a read workload when connecting. Enforces read only at connection time, and also for USE database statements.

Provider = MSOLEDBSQL; Server = tcp:AvailabilityGroupListenerDnsName,1433; MultiSubnetFailover = Yes; ApplicationIntent = ReadOnly; Database = MyDB; Integrated Security = SSPI; Connect Timeout = 30;

The result of using ApplicationIntent depends on database configuration. See read-only routing. The default for ApplicationIntent is ReadWrite.

Read-Only routing

You can either use an availability group listener for Server OR the read-only instance name to enforce a specific read-only instance.

Provider = MSOLEDBSQL; Server = aKnownReadOnlyInstance; MultiSubnetFailover = Yes; ApplicationIntent = ReadOnly; Database = MyDB; Integrated Security = SSPI; Connect Timeout = 30;

An availability group must enable read-only routing for this to work.

SQL Server Native Client 11.0 OLE DB Provider

Standard security

Are you using SQL Server 2012 Express? Don’t miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2012 Express installation resides.

Trusted connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Provider = SQLNCLI11; Server = myServerName\theInstanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Provider = SQLNCLI11; Server = myServerName,myPortNumber; Database = myDataBase; Uid = myUsername; Pwd = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Provider = SQLNCLI11; Data Source = myServerAddress; Failover Partner = myMirrorServerAddress; Initial Catalog = myDataBase; Integrated Security = True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

SQL Server Native Client 10.0 OLE DB Provider

Standard security

Are you using SQL Server 2008 Express? Don’t miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2008 Express installation resides.

Trusted connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Provider = SQLNCLI10; Server = myServerName\theInstanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Provider = SQLNCLI10; Server = myServerName,myPortNumber; Database = myDataBase; Uid = myUsername; Pwd = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Provider = SQLNCLI10; Data Source = myServerAddress; Failover Partner = myMirrorServerAddress; Initial Catalog = myDataBase; Integrated Security = True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

SQL Native Client 9.0 OLE DB Provider

Standard security

Are you using SQL Server 2005 Express? Don’t miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.

Trusted connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Provider = SQLNCLI; Server = myServerName\theInstanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Provider = SQLNCLI; Server = myServerName,myPortNumber; Database = myDataBase; Uid = myUsername; Pwd = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Provider = SQLNCLI; Data Source = myServerAddress; Failover Partner = myMirrorServerAddress; Initial Catalog = myDataBase; Integrated Security = True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Microsoft OLE DB Provider for SQL Server

Standard Security

Trusted connection

Use serverName\instanceName as Data Source to use a specific SQL Server instance. Please note that the multiple SQL Server instances feature is available only from SQL Server version 2000 and not in any previous versions.

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Provider = sqloledb; Data Source = myServerName\theInstanceName; Initial Catalog = myDataBase; Integrated Security = SSPI;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Provider = sqloledb; Server = myServerName,myPortNumber; Database = myDataBase; User Id = myUsername; Password = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Prompt for username and password

This one is a bit tricky. First set the connection object’s Provider property to «sqloledb». Thereafter set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

oConn.Provider = «sqloledb»
oConn.Properties(«Prompt») = adPromptAlways

oConn.Open «Data Source=myServerAddress;Initial Catalog=myDataBase;»

Connect via an IP address

DBMSSOCN=TCP/IP. This is how to use TCP/IP instead of Named Pipes. At the end of the Data Source is the port to use. 1433 is the default port for SQL Server. Read more in the article How to define which network protocol to use.

Disable connection pooling

This one is usefull when receving errors «sp_setapprole was not invoked correctly.» (7.0) or «General network error. Check your network documentation» (2000) when connecting using an application role enabled connection. Application pooling (or OLE DB resource pooling) is on by default. Disabling it can help on this error.

Provider = sqloledb; Data Source = myServerAddress; Initial Catalog = myDataBase; User ID = myUsername; Password = myPassword; OLE DB Services = -2;

.NET Framework Data Provider for OLE DB

Use an OLE DB provider from .NET

See the respective OLEDB provider’s connection strings options. The .net OleDbConnection will just pass on the connection string to the specified OLEDB provider. Read more here.

Microsoft ODBC Driver 17 for SQL Server

Standard security

Using SQL Server Express? The server name syntax is ServerName\SQLEXPRESS where you substitute ServerName with the name of the server where SQL Server Express is running.

Trusted Connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Driver = ; Server = serverName\instanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Driver = ; Server = myServerName,myPortNumber; Database = myDataBase; UID = myUsername; PWD = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Driver = ; Server = myServerAddress; Failover_Partner = myMirrorServerAddress; Database = myDataBase; Trusted_Connection = yes;

This one is working only on Windows, not on macOS or Linux. There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Please note if you are using TCP/IP (using the network library parameter) and database mirroring, including port number in the address (formed as servername,portnumber) for both the main server and the failover partner can solve some reported issues.

Microsoft ODBC Driver 13 for SQL Server

Standard security

Using SQL Server Express? The server name syntax is ServerName\SQLEXPRESS where you substitute ServerName with the name of the server where SQL Server Express is running.

Trusted Connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Driver = ; Server = serverName\instanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Driver = ; Server = myServerName,myPortNumber; Database = myDataBase; UID = myUsername; PWD = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Driver = ; Server = myServerAddress; Failover_Partner = myMirrorServerAddress; Database = myDataBase; Trusted_Connection = yes;

This one is working only on Windows, not on macOS or Linux. There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Please note if you are using TCP/IP (using the network library parameter) and database mirroring, including port number in the address (formed as servername,portnumber) for both the main server and the failover partner can solve some reported issues.

Microsoft ODBC Driver 11 for SQL Server

Standard security

Using SQL Server Express? The server name syntax is ServerName\SQLEXPRESS where you substitute ServerName with the name of the server where SQL Server Express is running.

Trusted Connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Driver = ; Server = serverName\instanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Driver = ; Server = myServerName,myPortNumber; Database = myDataBase; UID = myUsername; PWD = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Driver = ; Server = myServerAddress; Failover_Partner = myMirrorServerAddress; Database = myDataBase; Trusted_Connection = yes;

This one is working only on Windows, not on macOS or Linux. There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Please note if you are using TCP/IP (using the network library parameter) and database mirroring, including port number in the address (formed as servername,portnumber) for both the main server and the failover partner can solve some reported issues.

SQL Server Native Client 11.0 ODBC Driver

Standard security

Are you using SQL Server 2012 Express? Don’t miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2012 Express installation resides.

Trusted Connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Driver = ; Server = myServerName\theInstanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Driver = ; Server = myServerName,myPortNumber; Database = myDataBase; Uid = myUsername; Pwd = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Driver = ; Server = myServerAddress; Failover_Partner = myMirrorServerAddress; Database = myDataBase; Trusted_Connection = yes;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Please note if you are using TCP/IP (using the network library parameter) and database mirroring, including port number in the address (formed as servername,portnumber) for both the main server and the failover partner can solve some reported issues.

SQL Server Native Client 10.0 ODBC Driver

Standard security

Are you using SQL Server 2008 Express? Don’t miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2008 Express installation resides.

Trusted Connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Driver = ; Server = myServerName\theInstanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Driver = ; Server = myServerName,myPortNumber; Database = myDataBase; Uid = myUsername; Pwd = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Driver = ; Server = myServerAddress; Failover_Partner = myMirrorServerAddress; Database = myDataBase; Trusted_Connection = yes;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Please note if you are using TCP/IP (using the network library parameter) and database mirroring, including port number in the address (formed as servername,portnumber) for both the main server and the failover partner can solve some reported issues.

SQL Native Client 9.0 ODBC Driver

Standard security

Are you using SQL Server 2005 Express? Don’t miss the server name syntax Servername\SQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.

Trusted Connection

Equivalent key-value pair: «Integrated Security=SSPI» equals «Trusted_Connection=yes»

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Driver = ; Server = myServerName\theInstanceName; Database = myDataBase; Trusted_Connection = yes;

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Driver = ; Server = myServerName,myPortNumber; Database = myDataBase; Uid = myUsername; Pwd = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

Enable MARS

Encrypt data sent over network

Attach a database file on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Driver = ; Server = myServerAddress; Failover_Partner = myMirrorServerAddress; Database = myDataBase; Trusted_Connection = yes;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Please note if you are using TCP/IP (using the network library parameter) and database mirroring, including port number in the address (formed as servername,portnumber) for both the main server and the failover partner can solve some reported issues.

Microsoft SQL Server ODBC Driver

Standard Security

Trusted connection

Using a non-standard port

If your SQL Server listens on a non-default port you can specify that using the servername,xxxx syntax (note the comma, it’s not a colon).

Driver = ; Server = myServerName,myPortNumber; Database = myDataBase; Uid = myUsername; Pwd = myPassword;

The default SQL Server port is 1433 and there is no need to specify that in the connection string.

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

.NET Framework Data Provider for ODBC

Use an ODBC driver from .NET

See the respective ODBC driver’s connection strings options. The .net OdbcConnection will just pass on the connection string to the specified ODBC driver. Read more here.

SQLXML 4.0 OLEDB Provider

With Microsoft OLE DB Driver for SQL Server (MSOLEDBSQL)

The DataTypeCompatibility=80 is important for the XML types to be recognised by ADO.

Provider = SQLXMLOLEDB.4.0; Data Provider = MSOLEDBSQL; DataTypeCompatibility = 80; Data Source = myServerAddress; Initial Catalog = myDataBase; User Id = myUsername; Password = myPassword;

See also the other options available for MSOLEDBSQL connection strings.

Using SQL Server Native Client provider 11 (SQLNCLI11)

Using SQL Server Native Client provider 10 (SQLNCLI10)

Using SQL Server Native Client provider (SQLNCLI)

SQLXML 3.0 OLEDB Provider

Using SQL Server Ole Db

The SQLXML version 3.0 restricts the data provider to SQLOLEDB only.

Provider = SQLXMLOLEDB.3.0; Data Provider = SQLOLEDB; Data Source = myServerAddress; Initial Catalog = myDataBase; User Id = myUsername; Password = myPassword;

Context Connection

Context Connection

Connecting to «self» from within your CLR stored prodedure/function. The context connection lets you execute Transact-SQL statements in the same context (connection) that your code was invoked in the first place.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *