Wrox Home  
Search P2P Archive for: Go

  Return to Index  

aspx_beginners thread: reusing connection/command objects


Message #1 by "John Tyson" <jtyson@t...> on Thu, 17 Oct 2002 13:43:10 -0700
Hi there,

I've tried this, but I can't seem to figure out how to simply reuse the
connection and command objects in my subroutine instead of creating more
than one.  Can anyone help me with the syntax using the code below as an
example?  Thank you very much.

<script language=3D"VB" runat=3D"server">

   Sub Page_Load(s As Object, e As EventArgs)

      Dim dbconn As SqlConnection =3D New SqlConnection _
      (ConfigurationSettings.AppSettings("ConnectionString2"))

      Dim cmd As SqlCommand =3D New SqlCommand("GET_facilityName", 
dbconn)
      cmd.CommandType =3D CommandType.StoredProcedure

      Dim facNameParam As SqlParameter =3D 
cmd.Parameters.Add("@facName",
SqlDbType.NVarChar, 75)
      facNameParam.Direction =3D ParameterDirection.Output

      Dim facIdParam As SqlParameter =3D cmd.Parameters.Add("@facID",
SqlDbType.Int, 4)
      facIdParam.Direction =3D ParameterDirection.Input
      facIdParam.Value =3D CInt(Request.Params("id"))

      Try   
         dbconn.Open()
         cmd.ExecuteNonQuery()

      Catch SQLexc As SQLexception
         Response.Write("An error has occurred: " & SQLexc.ToString())

      Catch exc As Exception
         Response.Write("An error has occurred: " & exc.ToString())

      Finally
         dsplFacName.InnerHtml =3D cmd.Parameters("@facName").Value

         If dbconn.State =3D ConnectionState.Open Then
            dbconn.close()
         End If
      End Try


      Dim dbconn2 As SqlConnection =3D New SqlConnection _
      (ConfigurationSettings.AppSettings("ConnectionString1"))

      Dim cmd2 As SqlCommand =3D New SqlCommand("GET_facilityMenu",
dbconn2)
      cmd2.CommandType =3D CommandType.StoredProcedure

      Dim usrIdParam As SqlParameter =3D cmd2.Parameters.Add("@usrID",
SqlDbType.NVarChar, 10)
      usrIdParam.Direction =3D ParameterDirection.Input
      usrIdParam.Value =3D CStr(User.Identity.Name)

      Dim dr As SqlDataReader

      Try
         dbconn2.Open()
         dr =3D cmd2.ExecuteReader(CommandBehavior.CloseConnection)

         lstFacMenu.DataSource =3D dr
         lstFacMenu.DataBind()

      Catch SQLexc As SQLexception
         Response.Write("An error has occurred: " & SQLexc.ToString())

      Catch exc As Exception
         Response.Write("An error has occurred: " & exc.ToString())

      Finally
         If Not dr Is Nothing Then
            dr.Close()
         End If

         If dbconn2.State =3D ConnectionState.Open Then
            dbconn2.close()
         End If
      End Try

   End Sub

</script>

  Return to Index