数据库搜索功能

时间:2009-09-08 11:29:20

标签: asp.net vb.net

我想从sql数据库中搜索一个记录的名字,所以我在数据层中使用了一个函数,但它无法正常工作请纠正我的错误,这里是我的功能:

Public Function searchCustomer(ByVal custFname As String) As DataTable
            Dim tabletdata As New DataTable
            Dim conn As New SqlConnection(con_string)
            conn.Open()
            Dim dCmd As New SqlCommand("selectCustomerByFname", conn)
            dCmd.CommandType = CommandType.StoredProcedure
            Try
                dCmd.Parameters.AddWithValue("@Cust_Fnam", custFname)
                'dCmd.ExecuteNonQuery()
                Dim dadaptr As New SqlDataAdapter(dCmd)
                dadaptr.SelectCommand = dCmd
                dadaptr.SelectCommand.ExecuteNonQuery()
                dadaptr.Fill(tabletdata)


                Return tabletdata
            Catch
                Throw
            Finally
                dCmd.Dispose()
                conn.Close()
                conn.Dispose()
            End Try

        End Function 

1 个答案:

答案 0 :(得分:1)

填充方法隐式打开和关闭连接。 Fill Method

  

摘要:Fill方法检索   来自数据源的行使用   由一个指定的SELECT语句   关联的SelectCommand属性。该   与之关联的连接对象   SELECT语句必须有效,但它   不需要打开。如果   连接在Fill之前关闭   调用,它被打开以检索数据,   然后关闭如果连接已打开   在调用Fill之前,它仍然存在   开。

Public Function searchCustomer(ByVal custFname As String) As DataTable
  Dim tabletdata As New DataTable
  Dim conn As New SqlConnection(con_string)
  Dim dCmd As New SqlCommand("selectCustomerByFname", conn)
  dCmd.CommandType = CommandType.StoredProcedure

  dCmd.Parameters.AddWithValue("@Cust_Fnam", custFname)
  Dim dadaptr As New SqlDataAdapter(dCmd)
  dadaptr.SelectCommand = dCmd
  dadaptr.Fill(tabletdata)
  Return tabletdata
End Function