[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1209
  • Last Modified:

Reusing the SQLCommand in vb.net

I am using the sqlcommand often to execute queries on the SQL Server from my vb.net program.  The problem I am having is that I have to keep retyping my commands.  See below.  Rather then redimming my commmands everytime is there a way to reuse them for ex. I want to reuse the cmd rather than renaming it to cmdprior.  Also same applies to the irowsaffected variable.

 Dim cmd As SqlCommand = New SqlCommand
        Dim irowsaffected As Integer

        cmd.CommandTimeout = "60"
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "select count(*) from jcpmst1"
        cmd.Connection = sqlupdate

        sqlupdate.Open()
        irowsaffected = cmd.ExecuteScalar
        sqlupdate.Close()
        cmd = Nothing

 Dim cmdprior As SqlCommand = New SqlCommand
                    Dim irowsaffected3 As Integer
                    cmdprior.CommandTimeout = "90"
                    cmdprior.CommandText = "Delete from prior"
                    cmdprior.CommandType = CommandType.Text
                    cmdprior.Connection = sqlupdate
                    sqlupdate.Open()
                    irowsaffected3 = cmdprior.ExecuteNonQuery
                    sqlupdate.Close()
                    cmdprior = Nothing
                    irowsaffected3 = Nothing


Thanks
Tim
0
tbailey922
Asked:
tbailey922
1 Solution
 
RonaldBiemansCommented:
you mean like this

Dim cmd As SqlCommand = New SqlCommand


       Dim irowsaffected As Integer
        cmd.CommandTimeout = "60"
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "select count(*) from jcpmst1"
        cmd.Connection = sqlupdate

        sqlupdate.Open()
        irowsaffected = cmd.ExecuteScalar
        sqlupdate.Close()


                    cmd.CommandTimeout = "90"
                    cmd.CommandText = "Delete from prior"
                    cmd.CommandType = CommandType.Text
                    cmd.Connection = sqlupdate
                    sqlupdate.Open()
                    irowsaffected = cmd.ExecuteNonQuery
                    sqlupdate.Close()
                    cmd = Nothing
                    irowsaffected = Nothing
0
 
tbailey922Author Commented:
Exactly!

Thanks
Tim
0

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

Tackle projects and never again get stuck behind a technical roadblock.
Join Now