使用连接字符串中的服务器名称参数指定客户端网络库

摘要

本文介绍如何在连接到 SQL Server 数据库时以编程方式在 连接字符串中指定客户端网络库。

在 Microsoft 数据访问组件 (MDAC) 2.6 及更高版本中,可以使用 连接字符串 中的服务器名称参数指定客户端访问库。 因此,当应用程序提示你输入要连接到的服务器名称时,可以指定特定的客户端访问库。 在测试和排查SQL Server的连接问题时,此行为非常有用。

例如,可以使用 Osql 命令行实用工具连接到SQL Server并强制它使用 TCP/IP 网络库:

osql -Stcp:myServer,portNumber -E

原始产品版本:SQL Server
原始 KB 编号: 313295

代码示例

以下 Microsoft Visual C# .NET 代码示例演示如何设置连接字符串。 无论使用哪种语言,连接字符串都具有相同的格式:

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

namespace getCurrentProtocol
{
    /// <summary>
    /// Main Application Driver Class
    /// </summary>
    class Driver
    {
        static void Main(string[] args)
        {
            string sCxn = "server=myServer;Integrated Security=SSPI; database=master";
            //string sCxn = "server=np:myServer;Integrated Security=SSPI; database=master";
            //string sCxn = "server=tcp:myServer;Integrated Security=SSPI; database=master";
            //string sCxn = "server=rpc:myServer;Integrated Security=SSPI; database=master";
            //string sCxn = "server=lpc:myServer;Integrated Security=SSPI; database=master";
            string sCmd = "SELECT net_library from sysprocesses where spid=@@spid";
            SqlConnection cxn = new SqlConnection(sCxn);
            SqlCommand sqlCmd = new SqlCommand(sCmd, cxn);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sCmd, cxn);
            DataTable dt = new DataTable();
            try 
            {
                sqlDa.Fill(dt);
                Console.WriteLine("Hit ENTER to continue ...");
                Console.ReadLine();
                foreach (DataRow dr in dt.Rows)
                Console.WriteLine(dr["net_library"]);
            } 
            catch (SqlException e)
            {
                Console.WriteLine(e.StackTrace);
                Console.WriteLine("SQL Error Number: " + e.Number);
                Console.WriteLine("SQL Error Message: " + e.Message);
            }
        }
    }
}

注意

连接字符串,尤其是服务器参数的值:

string sCxn = "server=myServer;Integrated Security=SSPI; database=northwind"

将代码示例与各种网络库配合使用

以下代码示例演示如何使用服务器参数的值来指定各种网络库:

  • TCP/IP:

    server=tcp:hostname
    

    可以选择指定特定的端口号。 默认情况下,端口为 1433。

    server=tcp:hostname, portNumber
    
  • 命名管道:

    server=np:hostname
    

    可以选择指定特定的命名管道。

    server=np:\\hostname\pipe\pipeName
    

    默认情况下,管道名称为 sql\query。 如果连接到命名实例,管道名称通常采用以下格式:

    MSSQL$instnaceName\sql\query

  • 基础协议的默认值由操作系统设置确定,其中协议可以具有以下任何一个值:

    基础协议
    ncacn_np 命名管道
    ncacn_ip_tcp 传输控制协议/Internet 协议 (TCP/IP)
    ncalrpc 本地过程调用
  • 共享内存:

    server=lpc:hostname
    

References

有关详细信息,请参阅 附录 A:注册表项