异步访问数据库(经典之三)

 

异步访问数据库(经典之三)

本测试不作说明 ,原本个人内部使用

    Public Delegate Function SQLOp(ByVal pSql As String) As DataSet

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
         Dim b As SQLOp = New SQLOp(AddressOf RunSql)
         Dim itFAR As IAsyncResult = b.BeginInvoke("select * from tbuser", New AsyncCallback(AddressOf AddComplete), "添加完成!")

    End Sub

    Sub AddComplete(ByVal itFar As IAsyncResult)
  
      Dim ar As AsyncResult = CType(itFar, AsyncResult)
        Dim b As SQLOp = CType(ar.AsyncDelegate, SQLOp)

        myDs = CType(b.EndInvoke(itFar), DataSet)

        Console.WriteLine("结果正确!")

        Dim msg As String = CType(itFar.AsyncState, String)
        Console.WriteLine(msg)

    End Sub

       Function RunSql(ByVal pSql As String) As DataSet
        Dim m_ConnectionString As String = String.Empty
        '创建一个OleDbConnection对象
        Dim m_Connection As New SqlConnection
        Dim m_Command As New SqlCommand
        Try
            m_Connection.ConnectionString = "Data Source=WANGLI;Initial Catalog=Newdb;Persist Security Info=True;User ID=sa; PassWord=sa;Asynchronous Processing=True"
            '用SqlConnection对象和数据库打开连接
            m_Connection.Open()
            '定义Command对象将执行SQL
            m_Command.Connection = m_Connection
            m_Command.CommandType = CommandType.Text
            m_Command.CommandText = pSql

            Dim ds As New DataSet
            Dim da As New System.Data.SqlClient.SqlDataAdapter
            da.TableMappings.Add("Table", "TEMP")
            da.SelectCommand = m_Command
            da.Fill(ds)

            Return ds

        Catch ex As Exception
            Throw New Exception(ex.Message)
            Return Nothing
        Finally
            '关闭SqlConnection对象
            m_Connection.Close()
        End Try

    End Function

你可能感兴趣的:(vb.net异步操作,编程技巧)