本文可協助您解決當您使用 TCP/IP 以外的通訊協定連線到 1433 以外的埠上的 SQL Server 時所發生的問題。
原始產品版本: Visual C#
原始 KB 編號: 307645
徵兆
當您使用傳輸控制通訊協定/因特網通訊協定(TCP/IP)以外的通訊協定時, SqlConnection.Open 如果您指定 1433 以外的埠號碼來連線到 SQL Server 實例,就會失敗。
解決方法
若要解決此問題,請使用 TCP/IP 通訊協定,並在 連接字串 中包含 Server=ComputerName, PortNumber 。
重現行為的步驟
啟動 Visual Studio .NET。
建立新的 Visual C# .NET 控制台應用程式專案。
請確定您的專案包含命名空間的
System.Data參考,如果不是,請新增此命名空間的參考。在、
System.DataSystem.Data.SqlClient命名空間上使用Systemusing 語句,因此您不需要在程式代碼稍後限定這些命名空間中的宣告。using System; using System.Data; using System.Data.SqlClient;Visual Studio 預設會建立靜態類別和空白
Main程式。 複製下列程式代碼,並將其貼到 [程序代碼] 視窗中:注意
您必須先將
User ID<username>值和密碼<strong password>值變更為正確的值,才能執行此程序代碼。 請確定User ID具有在資料庫上執行這項作業的適當許可權。class Class1 { static void Main(string[] args) { string sConnectionString; sConnectionString = "User ID=<username>;Password =<strong password>;Initial Catalog=pubs;Data Source=myServer,1200"; SqlConnection objConn = new SqlConnection(sConnectionString); objConn.Open(); SqlDataAdapter daAuthors = new SqlDataAdapter("Select * From Authors", objConn); DataSet dsPubs = new DataSet("Pubs"); daAuthors.FillSchema(dsPubs, SchemaType.Source, "Authors"); daAuthors.Fill(dsPubs, "Authors"); daAuthors.MissingSchemaAction = MissingSchemaAction.AddWithKey; daAuthors.Fill(dsPubs, "Authors"); DataTable tblAuthors; tblAuthors = dsPubs.Tables["Authors"]; foreach (DataRow drCurrent in tblAuthors.Rows) { Console.WriteLine("{0} {1}", drCurrent["au_fname"].ToString(), drCurrent["au_lname"].ToString()); } Console.ReadLine(); } }sConnectionString根據您的環境適當地修改字串。儲存您的專案。
在 [偵錯] 功能表上,單擊 [開始],然後執行您的專案以聯機到資料庫。