2016-03-13 66 views
0

之前,我不知道爲什麼我越來越從Visual Studio的警告下面的代碼:變量X已被使用,它已經宣佈

Dim cmd As SqlCommand 
cmd.Parameters.AddWithValue("@password", pw.tostring) 
Try 
      myconn.open 
      cmd = New SqlCommand("UPDATE Customers SET [email protected] WHERE [email protected]", myconn) 

這是警告消息,我得到: 嚴重級代碼說明項目文件行抑制狀態 警告BC42104在爲其指定值之前使用變量「Cmd」。運行時可能會導致空引用異常。
感謝所有幫助

回答

3

您正在訪問CMD的參數屬性:

Dim cmd As SqlCommand 
cmd.Parameters.AddWithValue("@password", pw.tostring) ' <== You can't use cmd yet! 

您在嘗試實例化之前:

Try 
     myconn.open 

     ' This is where you are instantiating the object instance: 
     cmd = New SqlCommand("UPDATE Customers SET [email protected] WHERE [email protected]", myconn) 

如果你改變這一點,它會工作:

Dim cmd As SqlCommand 
cmd = New SqlCommand("UPDATE Customers SET [email protected] WHERE [email protected]", myconn) 

' You could combine the two above lines into one like this: 
'Dim cmd As New SqlCommand("UPDATE Customers SET [email protected] WHERE [email protected]", myconn) 

cmd.Parameters.AddWithValue("@password", pw.tostring) 

    Try 
     myconn.open 

這也更好,因爲只有myconn.open指令應該在Try/Catch中,因爲它是唯一可能導致異常的行。 Try/Catch應該僅用於可能通過開發人員的錯誤導致異常的代碼。向命令添加參數不會那樣做,但實際的數據庫交互可以。

+0

謝謝你的答案。我從這麼小的代碼中學到了很多東西:D ps:一旦它讓我接受答案 – Quattro

相關問題