2012-01-31 202 views
1

我很難從IIS7對Server 2008的SQL查詢。我有一個運行更新語句的VB.NET類庫。用於創建連接的底層代碼沒有改變,但突然間,查詢在我們的測試和開發環境中失敗。但是,它仍然在使用我們的生產環境中稍舊的代碼的同一臺服務器/數據庫上工作。強制關閉SQL連接

我試過設置在web.config中的連接超時,我茫然地解釋原因。

查詢的基本結構是:

Dim conn = New SqlConnection() 
conn.ConnectionString = "Data Source=someserver\sqlexpress2008;Initial Catalog=DatabaseName;User ID=sa;Password=pass" 
conn.Open() 
Using cmd As SqlCommand = conn.CreateCommand() 
    cmd.CommandText = "UPDATE ..." 
    cmd.Parameters.AddWithValue("@UName", user.name) 
    cmd.ExecuteNonQuery() 'fails with error 
End Using 

的錯誤是:

A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)

我試着重新啓動IIS和SQL服務器和我完全沒了主意。我只需要一個修復程序

+0

你可以運行其他命令在代碼中的其他地方使用相同的連接字符串嗎?也就是說,我們可以確認您的實際連接字符串是否有效? – DOK 2012-01-31 14:30:14

+0

是的,代碼通過SMSS和Web應用程序的其他部分工作。 – Echilon 2012-01-31 14:33:00

回答

1

這是一場噩夢追查。事實證明,這是VB.NET中可怕的怪癖造成的。可空的日期時間似乎被強制爲DateTime.MinValue,導致DateTime.MinValue被插入sql datetime。修復方法是在設置命令的參數時檢查!property.HasValue && property.Value != DateTime.MinValue

+0

看不到這會導致連接錯誤...我希望能產生一些錯誤,但不是你所得到的錯誤。 – 2012-02-02 14:13:44

+0

這正是我所困惑的,但是當我將值更改爲DBNull.Value時,查詢正常工作。 – Echilon 2012-02-03 14:21:12

+0

你採取了哪些步驟來得出這個結論? – schummbo 2015-07-04 20:23:38

2

您需要先打開連接,然後致電SqlCommand.ExecuteNonQuery()。您可以撥打SqlConnection.Open()來完成此操作。

Dim conn = New SqlConnection() 
conn.ConnectionString = "Data Source=someserver\sqlexpress2008;Initial Catalog=DatabaseName;User ID=sa;Password=pass" 
Using cmd As SqlCommand = conn.CreateCommand() 
    cmd.CommandText = "UPDATE ..." 
    cmd.Parameters.AddWithValue("@UName", user.name) 

    conn.Open() 
    cmd.ExecuteNonQuery() 'fails with error 
    conn.Close() 
End Using 

此外,請確保您的數據庫不處於單用戶模式。

+0

道歉,連接是開放的,我忽略了那條線。 – Echilon 2012-01-31 14:28:18

+0

@Echilon您的數據庫可能處於單用戶模式?嘗試通過SSMS建立多個連接。 – 2012-01-31 14:29:23

0

這是一個網絡級錯誤。由於某種原因,數據庫服務器正在終止連接。爲了解決這個問題,我會打開一個使用SSMS連接到DEV和TEST服務器的連接,並確保我可以運行無問題的簡單查詢。這個問題不太可能是你的圖書館,因爲你會得到超時或其他類型的錯誤。

2

這幫助了最近被卡住的另一個人。您可以通過設置SQL Server Profiler來檢查數據庫服務器中的問題。

只需使用Google搜索,您可以找到許多關於SQL Profiler的信息。這裏有一個site with a video,可以幫助你開始。對於初學者,您將能夠看到請求是否到達數據庫服務器。

+0

+1偉大的建議來運行SQL跟蹤。 – 2012-01-31 15:34:39

0

作爲Lcarus表示,數據庫服務器正在查找未知原因的連接。 你可以檢查日誌,以確定。日誌路徑將是C:\Program Files\Microsoft SQL Server\<your instance>\MSSQL\LOG

從MSDN博客MSDN Blog

this will occur when A connection is taken from the connection pool, the application does not know that the physical connection is gone, an attempt to use it is done under the assumption that the physical connection is still there.