SQL Server Connection Strings, and Why I Build Them the Way I Do

A script reads instance names from a text file and connects to each one with a string like this:

A woman DBA fits pipe segments into matching slots on a workbench, and a gold-sleeved pipe runs to a database cylinder whose gold seal she compares with the matching seal on a card in her hand.

If someone adds the line .\SQL2019;Connect Timeout=1;Pooling=False to that file, the script connects to that instance with a one-second login timeout and without connection pooling. The connection succeeds, and nothing in the output shows that the options changed.

In early November I updated several posts on this site so that every SQL Server connection in them uses a connection string builder and sets Encrypt. None of them sets TrustServerCertificate now without saying what it allows.

I tested on one Windows 11 workstation with SQL Server 2019 (15.0.4500.2) and SQL Server 2025 (17.0.5015.4), using Windows authentication and read-only queries. Neither instance has a certificate from a certificate authority (CA), and each ERRORLOG shows “A self-generated certificate was successfully loaded for encryption” at the last start. The clients were System.Data.SqlClient in Windows PowerShell 5.1 and PowerShell 7.6.9, ODBC Driver 18 (18.7.1.1), two builds of sqlcmd, and Microsoft.Data.SqlClient 6.1.4 in a .NET 8 program. I changed the instance and workstation names in the output to SQL2019, SQL2025 and SQLDEV01. I also tested two keywords against a test availability group, which has its own section below.

Let the Builder Quote the Values

I build connection strings with SqlConnectionStringBuilder out of habit. A connection string is a list of keyword=value pairs separated by semicolons, so a value that contains a semicolon can add keywords of its own. Microsoft calls this connection string injection. The parser uses a “last one wins” algorithm, so a hostile value can replace a legitimate one.[1]

I put three values for $instance into "Server=$instance;Database=master;Integrated Security=True;Application Name=connstr_probe", parsed each result with the builder, and opened a connection with it. Both instances gave the same results:

Value of $instance What happened
.\SQL2019;Database=msdb Connected to master, because the template’s later Database=master won.
.\SQL2019;Connect Timeout=1;Pooling=False Connected, with a one-second timeout and pooling off.
.\SQL2019;User ID=sa User ID parsed as sa, but Integrated Security=True still logged in with my Windows account.

The injected value lost only where the template set the same keyword later in the string. Keywords the template didn’t set took effect, and a string with Application Name in it twice used the second value.

With the builder, the same kind of input stays inside one value:

The builder quoted the whole value, so Encrypt=False became part of the server name, and opening the connection failed with error 26, “Error Locating Server/Instance Specified”.

Injection changes connection options, not the T-SQL a script runs. Those options include the server: with $instance set to .\SQL2019;Server=.\SQL2025, the script connected to SQL2025. Microsoft warns that an attacker may be able to use injection to reach sensitive data on the server.[1] By the same rule, an injected TrustServerCertificate=True would apply whenever the template doesn’t set it later in the string, although I didn’t test that one. The risk matters when any part of the string comes from a file, a table or a Central Management Server that someone else can edit.

In PowerShell, set values through the keyword indexer, as above. In both editions, $builder.DataSource = '.\SQL2019' failed with “Keyword not supported: ‘DataSource’.” Properties whose names are also keywords, such as Encrypt and TrustServerCertificate, worked either way.

OdbcConnectionStringBuilder does the same job for ODBC, and its documentation says the indexer handles attempts to insert malicious code.[2] With Server set to .\SQL2019;Encrypt=no, it wrapped the value in braces:

Set Encrypt Every Time

I want Encrypt=True on every connection to SQL Server. The default depends on the client:

  • System.Data.SqlClient: Encrypt is false unless you supply it.[3] An empty builder reported False in both PowerShell editions.
  • Microsoft.Data.SqlClient: version 4.0 changed the default to true.[4] An empty builder in my .NET 8 program reported True.
  • ODBC Driver 18: the default is yes, and versions before 18.0 default to no.[5]
  • sqlcmd: in SQL Server 2025, leaving out -N means -Nm (mandatory). The documentation calls this a breaking change from SQL Server 2022 and earlier, where the default is -No.[6]

If you set Encrypt yourself, the setting stays the same when a machine gets a different driver. Finding Unencrypted SQL Server Connections, and the Instances That Accept Them tested each driver’s default against these two instances, so I haven’t repeated that here.

What TrustServerCertificate Skips

Encrypt=True against my instances failed with “The certificate chain was issued by an authority that is not trusted.” One quick way to make that error go away is TrustServerCertificate=True. The driver still encrypts the channel, but it skips walking the certificate chain to validate trust.[7] Microsoft’s TDS 8.0 page marks the setting “not recommended”, and says strict encryption doesn’t allow it, to prevent a man-in-the-middle attack.[8]

These are the results over TCP, the same on both instances:

Client Setting Result encrypt_option
System.Data.SqlClient Encrypt=True certificate chain not trusted (no connection)
System.Data.SqlClient Encrypt=True, TrustServerCertificate=True connected TRUE
System.Data.SqlClient TrustServerCertificate=True only connected FALSE
ODBC Driver 18 Encrypt not set, or Encrypt=Yes certificate chain not trusted (no connection)
ODBC Driver 18 Encrypt=Yes, TrustServerCertificate=Yes connected TRUE
ODBC Driver 18 Encrypt=Optional connected FALSE
sqlcmd 15.0 (ODBC Driver 17) no -N or -C, or -C only connected FALSE
sqlcmd 15.0 (ODBC Driver 17) -N certificate chain not trusted (no connection)
sqlcmd 15.0 (ODBC Driver 17) -N -C connected TRUE
sqlcmd 17.0 (ODBC Driver 18) no -N or -C, or -N certificate chain not trusted (no connection)
sqlcmd 17.0 (ODBC Driver 18) -C, or -N -C connected TRUE
sqlcmd 17.0 (ODBC Driver 18) -No connected FALSE

TrustServerCertificate=True without Encrypt gave FALSE with System.Data.SqlClient, so that connection skipped validation and wasn’t encrypted either. The Microsoft.Data.SqlClient keyword reference says a connection with TrustServerCertificate true and Encrypt false isn’t encrypted.[9] In that driver, a missing Encrypt means true, so the same string encrypts there. -C alone gave FALSE with the older sqlcmd, and the documentation describes -C as the equivalent of TRUSTSERVERCERTIFICATE = true.[6] The newer sqlcmd encrypted with -C alone, because its default is mandatory.

TrustServerCertificate=True is fine for test instances like these. Don’t use it anywhere else without understanding that it allows a man-in-the-middle attack.[8] The fix is a server certificate from a CA that the clients trust. A client that has the CA’s certificate needs no further configuration, and a client that doesn’t needs it installed.[10] Even my home network has certificates that clients can validate: I run my own certificate authority, and I’ve distributed its certificate to the client machines.

If you connect with a name that isn’t on the certificate, such as a DNS alias, you can name the host to expect instead of turning validation off. That’s HostNameInCertificate in Microsoft.Data.SqlClient 5.0 and later,[9] HostnameInCertificate in ODBC Driver 18,[5] and -F in sqlcmd.[6]

Strict Encryption

Encrypt=Strict uses TDS 8.0, which SQL Server 2022 and later versions support. With TDS 8.0, the TLS handshake comes before the TDS prelogin, so the prelogin is encrypted too.[8] Microsoft.Data.SqlClient added Encrypt=Strict in version 5.0,[4] and ODBC Driver 18 accepts strict.[5] Under strict, Microsoft.Data.SqlClient ignores TrustServerCertificate and treats it as false.[9]

System.Data.SqlClient rejected Encrypt=Strict in both PowerShell editions as not a valid Boolean. Strict connections from the newer drivers failed on both instances, which the post on unencrypted connections explains.

Keywords Worth Knowing

Application Name sets program_name in sys.dm_exec_sessions[11] and the value APP_NAME() returns. With Application Name=connstr_probe_app, both showed that value. A distinct name lets you find a script’s sessions in the DMVs, and a Resource Governor classifier function can assign sessions to a workload group by APP_NAME().[12] APP_NAME() doesn’t verify the name, so don’t use it in a security check.[13] Keep it the same for every connection a workload opens, because the pooling documentation says to avoid per-request values in Application Name and Workstation ID.[14]

Workstation ID sets host_name, and defaults to the local computer name.[9] I set it to SQLLAB99, a name that doesn’t exist, and host_name and HOST_NAME() both returned SQLLAB99. The client provides the value and can provide inaccurate data, so don’t rely on it for security.[11]

Connect Timeout is how long the driver waits to open the connection, 15 seconds by default. The command timeout is how long it waits for a command, 30 seconds by default, and Microsoft.Data.SqlClient has a Command Timeout keyword for it.[9] With Command Timeout=7, CreateCommand() returned a command whose CommandTimeout was 7. System.Data.SqlClient rejected the keyword with “Keyword not supported: ‘command timeout'”, so set CommandTimeout on each command there.

ConnectRetryCount and ConnectRetryInterval control idle connection resiliency: how many times the client tries to reconnect after it detects that an idle connection failed, and how long it waits between attempts.[9] Both SqlClient builders reported defaults of 1 and 10 seconds.

Pooling, Max Pool Size and Min Pool Size default to true, 100 and 0.[9] The pool key includes the exact connection string text, so keywords in a different order get a separate pool.[14] In my test, two opens with one string left one session on the server, and the same keywords in another order added a second. Connection Pool Exhaustion: Reproducing the Timeout and What SQL Server Sees tests this in more detail. System.Data.SqlClient’s builder wrote its keywords in a fixed order, whatever order I set them in, so the same settings produced the same text.

Availability Group Listeners

I use MultiSubnetFailover and ApplicationIntent=ReadOnly every day. For this post I tested both against a test availability group I work with, on SQL Server 2019 CU32. It has two replicas, called SQLNODE01\APP and SQLNODE02\APP here, and a listener called SQLAG01-LSN, which I reach through a DNS alias. The listener has one IP address in each of two subnets, one online and one offline, and its DNS name returns both. In the primary role, each replica accepts only read-write connections. In the secondary role, it accepts all connections. Each replica has a READ_WRITE_ROUTING_URL, and its read-only routing list points at the other replica. The servers have CA-issued certificates, so Encrypt=True worked without TrustServerCertificate.

ApplicationIntent=ReadOnly declares the application workload type.[9] The sqlcmd equivalent is -K ReadOnly.[6] I opened each connection with System.Data.SqlClient and pooling off. I ran the listener rows in Windows PowerShell 5.1, and the rows that connect to a node in both editions, with the same results:

Connected to Intent Initial database Landed on Updateability
Listener read-write AppDB (in the AG) primary READ_WRITE
Listener ReadOnly AppDB secondary READ_ONLY
Listener ReadOnly UtilityDB (not in the AG) primary READ_WRITE
Listener ReadOnly master primary READ_WRITE
Secondary node read-write AppDB primary READ_WRITE
Primary node ReadOnly AppDB failed, Msg 979 (no connection)
Secondary node ReadOnly AppDB secondary READ_ONLY

Read-only routing happened only when the connection used the listener, read-only intent and a database in the availability group, which matches Microsoft’s conditions for it.[15] With master or a database outside the group as the initial catalog, a read-only connection stays on the primary.

The connection straight to the secondary node, without read intent, landed on the primary. That’s read/write connection redirection, which SQL Server 2019 introduced. It needs READ_WRITE_ROUTING_URL on the replica’s primary role, a secondary role that allows all connections, and a connection with read-write intent, whether set or left at the default.[16]

The connection to the primary node with read-only intent failed with Msg 979: “The target database (‘AppDB’) is in an availability group and currently does not allow read only connections.” A primary role set to ALLOW_CONNECTIONS = READ_WRITE refuses connections whose application intent is ReadOnly.[17] Read-only routing only happens through the listener,[15] so use the listener and an availability database as the initial catalog. Every connection that opened showed encrypt_option TRUE over TCP, with program_name set from the builder’s Application Name.

MultiSubnetFailover=True makes the driver open a TCP socket to each of the listener’s IP addresses in parallel and use the first one that responds. Microsoft recommends it for listeners and failover cluster instance names on one subnet or several, and it works only over TCP.[15] The sqlcmd equivalent is -M.[6]

I opened eight connections to the listener with MultiSubnetFailover=False and eight with True, in each PowerShell edition. All of them succeeded, in 196 to 331 ms, so the test didn’t show a cost for leaving the keyword off. In a separate run, the workstation’s DNS cache listed the offline address first, and a connection without MultiSubnetFailover still opened in 405 ms. I didn’t log which address that connection used. The cost can appear when the client tries the offline address first and waits for it to time out. An earlier script of mine timed out at the pre-login handshake until I added MultiSubnetFailover=True. Set it whenever you connect to a listener.

A Function That Puts It Together

This function uses Windows authentication, always sets Encrypt, and sets Application Name. -TrustServerCertificate is off by default, with a comment that it allows a man-in-the-middle attack.

Write-Output -NoEnumerate returns a DataTable even when the query returns no rows or one row. Passing DataTables Through the PowerShell Pipeline explains why that matters.

I ran it in Windows PowerShell 5.1 and PowerShell 7.6.9 against both instances:

Without the switch, it failed in both editions on both instances, with an error that contains this message:

With it, the connection was encrypted:

That’s shared memory, because the instance is local. With a tcp: prefix on the instance name, net_transport was TCP and encrypt_option was still TRUE. A query with no results still came back as a DataTable, with zero rows.

What I Tested and What I Didn’t

  • The local tests ran on two standalone instances on one workstation, with every connection local. The availability group tests ran from one workstation against one SQL Server 2019 availability group, with System.Data.SqlClient only.
  • I didn’t fail the availability group over, so I didn’t see MultiSubnetFailover handle a listener whose online address had moved.
  • Neither local instance has a CA-issued certificate, so I didn’t test HostNameInCertificate or a strict connection that succeeded.
  • I didn’t break an idle connection to watch ConnectRetryCount work.
  • I didn’t test Linux, Azure SQL Database, JDBC or the OLE DB driver.

Further Reading

If you set a connection string keyword on every connection that isn’t in this post, I’d like to hear which one and why. Find me on Bluesky or LinkedIn.

References

  1. Connection String Builders - ADO.NET - Microsoft Learn. Describes connection string injection through an appended semicolon, the “last one wins” parsing algorithm, and how SqlConnectionStringBuilder escapes an inserted value in double quotation marks. ↩
  2. OdbcConnectionStringBuilder Class - Microsoft Learn. States that the Item[] property handles attempts to insert malicious code, and that values containing a semicolon are delimited in the connection string. ↩
  3. SqlConnectionStringBuilder.Encrypt Property (System.Data.SqlClient) - Microsoft Learn. The property value is the value of Encrypt, “or false if none has been supplied.” ↩
  4. Introduction to the Microsoft.Data.SqlClient namespace - Microsoft Learn. States that version 4.0 changed Encrypt to default to true, and that version 5.0 introduced SqlConnectionEncryptOption and Encrypt=Strict for TDS 8.0. ↩
  5. ODBC DSN and Connection String Keywords - Microsoft Learn. The ODBC Encrypt keyword accepts mandatory, optional and strict from version 18.0, defaults to yes in 18.0 and later and to no in earlier versions, and HostnameInCertificate sets the host name to expect in the server’s certificate. ↩
  6. sqlcmd utility - Microsoft Learn. -N defaults to -Nm in SQL Server 2025, a breaking change from the -No default of SQL Server 2022 and earlier. -C is equivalent to TRUSTSERVERCERTIFICATE = true, -F sets the expected host name in the certificate, -M is for availability group listeners and failover cluster instances, and -K sets the application intent. ↩
  7. SqlConnectionStringBuilder.TrustServerCertificate Property (System.Data.SqlClient) - Microsoft Learn. When set to true, the transport layer encrypts the channel and bypasses walking the certificate chain to validate trust. ↩
  8. TDS 8.0 - Microsoft Learn. TDS 8.0 support from SQL Server 2022, the connection sequence with the TLS handshake before the prelogin, TrustServerCertificate marked “not recommended”, and the statement that strict encryption doesn’t allow TrustServerCertificate in order to prevent a man-in-the-middle attack. ↩
  9. SqlConnection.ConnectionString Property (Microsoft.Data.SqlClient) - Microsoft Learn. The keyword table, including Encrypt, TrustServerCertificate (not encrypted when Encrypt is false, ignored under strict), Host Name In Certificate (v5.0+), Application Intent, Workstation ID, Connect Timeout, Command Timeout, Connect Retry Count and Interval, pooling defaults and Persist Security Info. ↩
  10. Certificate requirements for SQL Server - Microsoft Learn. The client must be able to verify the server’s certificate. If it has the public key certificate of the CA that signed it, no further configuration is needed, and otherwise that CA certificate must be installed on each client. ↩
  11. sys.dm_exec_sessions (Transact-SQL) - Microsoft Learn. Defines host_name and program_name, with the security note that the client application provides the workstation name and can provide inaccurate data. ↩
  12. Resource governor classifier function - Microsoft Learn. Example C classifies sessions into a workload group with APP_NAME(), and notes that an application or user can provide any application name in the connection string. ↩
  13. APP_NAME (Transact-SQL) - Microsoft Learn. The client provides the application name, APP_NAME doesn’t verify it, and it shouldn’t be part of a security check. ↩
  14. SQL Server connection pooling with Microsoft.Data.SqlClient - Microsoft Learn. The pool key includes the exact connection string text, keyword order differences create separate pools, and the page recommends one canonical connection string without per-request values in Application Name or Workstation ID. ↩
  15. Connect to an availability group listener - Microsoft Learn. MultiSubnetFailover opens a TCP socket to each listener IP address in parallel, is recommended for single and multi-subnet listeners and failover cluster instance names, and works only over TCP. The read-only routing section lists the conditions for routing to a readable secondary. ↩
  16. Secondary to primary replica read/write connection redirection (Always On Availability Groups) - Microsoft Learn. SQL Server 2019 introduced read/write connection redirection, which sends a connection that targets a secondary replica to the primary. It requires READ_WRITE_ROUTING_URL in the replica’s PRIMARY_ROLE and a connection with ReadWrite intent, set or by default. Its table shows read-write connections routed to the primary when the secondary role allows all connections. ↩
  17. Configure read-only access to secondary availability group replica - Microsoft Learn. With PRIMARY_ROLE (ALLOW_CONNECTIONS = READ_WRITE), connections where the Application Intent property is ReadOnly are disallowed. ↩
  18. HannahVernon/sql-cert-inspector - GitHub. Source and releases for sql-cert-inspector. ↩
  19. HannahVernon/cert-auditor - GitHub. Mirror of the CertAuditor source. ↩