VB:SQL Query将结果返回到文本框

时间:2016-07-26 12:53:12

标签: sql sql-server vb.net visual-studio-2015

简而言之,我正在开发一个程序,用于向SQL数据库添加/编辑条目。

该程序的一个功能是,如果给定帐户ID号,它将在该帐户下查找具有该给定ID的名称。这就是我遇到的麻烦。

一般格式:

  • 目标:将字符串返回到文本框的SQL查询
  • AcctID =>表帐号中的字段
  • AcctName =>帐户名称
  • 表中的字段
  • txtbx_accountName =>文本框我需要返回的名称

注意:

  • 这些都嵌套在一个带有错误的通用Try-Catch语句中 处理
  • 这是一个按钮的Click事件处理程序。
  • 这一切都在Visual Studio 2015中完成
Dim myConn As New SqlConnection
Dim myCmd As New SqlCommand

myConn.ConnectionString = ""
myConn.Open() ' Open the connection
myCmd = myConn.CreateCommand()

' Build the query with the account number as paramter
myCmd.CommandText = "SELECT AcctName FROM DataSetTable WHERE (AcctID = @incomingAcctID)"
' Add the parameter so the SqlCommand can build the final query
myCmd.Parameters.Add(New SqlParameter("@incomingAcctID", (CInt(txtbx_accountNum.Text))))

' run the query and obtain a reader to get the results
Dim reader As SqlDataReader = myCmd.ExecuteReader()

' check if there are results
If (reader.Read()) Then
    ' populate the values of the controls
    txtbx_accountName.Text = reader(0)
End If

' Close all connections
myCmd.Dispose()
myConn.Close() ' Close connection
myConn.Dispose()

2 个答案:

答案 0 :(得分:0)

我不是亲,但我确实喜欢这个,抱歉,如果这对你没有帮助:

如果您创建的存储过程是为了添加和编辑而不是写入并将其调用到您要添加的位置:

    private sub NAME(ByVAL Parameter1 name as integer,
                     ByVAL Parameter2 name as string,
                     ByVAL Parameter3 name as boolean)

             Dim strConn As String = ConfigurationManager.ConnectionStrings("databaseXYZ").ConnectionString
             Dim myConn As New SqlConnection(strConn)
             Dim myCmd As SqlCommand

    try
            myConn.Open()
            sqlCommand = New SqlCommand("PRCEDURE_NAME", myConn )
            sqlCommand.CommandType = CommandType.StoredProcedure

            dim param as new System.Data.SqlClient.SqlParameter
            param.parameterName="@send_parameter1"
            param.Direction = ParameterDirection.Input
            param.Value = send_parameter1


            dim param1 as new System.Data.SqlClient.SqlParameter
            param1.parameterName="@send_parameter2"
            param1.Direction = ParameterDirection.Input
            param1.Value = send_parameter2

            sqlCommand.Parameters.Add(Param)
            sqlCommand.Parameters.Add(Param1)
            sqlCommand.ExecuteNonQuery()
   catch ex as exception
      throw
   End Try 
      myConn.Close()
      myConn = Nothing
  end sub

答案 1 :(得分:-1)

我是个假人!

以下是所有相关方的解决方案。

单击事件处理程序(带嵌套的Try-Catch):

txtbx_accountName.Text = DataSetTableAdapter.SearchNameQuery(CInt(txtbx_accountNum.Text)).ToString

SearchNameQuery:

SELECT AcctName FROM DataSetTable WHERE AcctID = @incomingAcctID

关于此的更多说明:   - 数据集已包含在项目中