簡體   English   中英

從VB.NET調用存儲過程時出現問題

[英]Problems calling a Stored Procedure from VB.NET

您可能很快就會看到,我是VB.NET的一名新手,我在從SQL Server 2005中的存儲過程獲取輸出時遇到了一些麻煩。

這是我使用的代碼

    Dim con As New SqlConnection
    Dim cmd As New SqlCommand("esp_getDates", con)
    Dim par As New SqlParameter("@PlaceID", SqlDbType.Int, 3906)
    con.ConnectionString = "Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test"
    con.Open()
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters("@PlaceID").Direction = ParameterDirection.Output
    cmd.ExecuteNonQuery()
    con.Close()

我得到了錯誤;

SqlParameterCollection不包含帶有ParameterName'@PlaceID'的SqlParameter。

有人看到我在做什么錯嗎/對如何解決它有任何建議嗎? 代碼示例將非常有幫助,任何幫助將不勝感激。

您實際上並沒有將參數添加到cmd.Parameters集合中:

cmd.Parameters.Add(par)

或者,只需添加參數而無需顯式實例化Parameter對象:

cmd.Parameters.Add("@PlaceID", SqlDbType.Int)
cmd.Parameters("@PlaceID").Value = 3906

另外,我將遵循使用變量盡可能接近聲明的原則,並以這種方式重新組織事情:

Dim con As New SqlConnection("Data Source=localhost\SQLEXPRESS;Initial Catalog=ProgramDB;User ID=test;Password=test")
con.Open()

Dim cmd As New SqlCommand("esp_getDates", con)

Try
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.Add("@PlaceID", SqlDbType.Int)
    cmd.Parameters("@PlaceID").Value = 3906
    cmd.ExecuteNonQuery()

Finally
    If cmd IsNot Nothing Then cmd.Dispose()
    If cn IsNot Nothing AndAlso cn.State <> ConnectionState.Closed Then cn.Close()
End Try

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM