HOW TO: Reuse the SqlCommand and OleDbCommand Objects in Visual Basic .NET (317150)



The information in this article applies to:

  • Microsoft ADO.NET (included with the .NET Framework 1.1)
  • Microsoft ADO.NET (included with the .NET Framework) 1.0
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

This article was previously published under Q317150
For a Microsoft Visual C# .NET version of this article, see 317559.

This article refers to the following Microsoft .NET Framework Class Library namespaces:
  • System.Data
  • System.Data.SqlClient

IN THIS TASK

SUMMARY

This step-by-step article describes how to reuse the SqlCommand object in your Visual Basic .NET code.

back to the top

Description of the Technique

You can reuse Command objects (SqlCommand or OleDbCommand) in code. That is, you can create one Command object and then run different commands on that object.

Commands are issued against databases to take actions against data stores. Commands include any statement that can be issued against a database. You can use the OleDbCommand or the SqlCommand class to get a command for your data store.

In Microsoft ActiveX Data Objects (ADO), you can issue commands through the Command, the Connection, or the Recordset object. In Microsoft ADO.NET, only the Command objects (SqlCommand or OleDbCommand) run commands.

back to the top

Steps to Reuse a SqlCommand Object

  1. Create a new Windows application in Visual Basic .NET as follows:
    1. Start Microsoft Visual Studio .NET.
    2. On the File menu, point to New, and then click Project.
    3. In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Windows Application under Templates. Form1 is added to the project by default.
  2. Make sure that your project contains a reference to the System.Data namespace. If it does not, add a reference to this namespace.
  3. Drag a Button control from the toolbox to Form1. Change the Name property of the button to btnTest.
  4. Use the Imports statement on the System and the System.Data namespaces so that you are not required to qualify declarations in those namespaces later in your code. Add the following code to the "General Declarations" section of Form1:
    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    					
  5. Copy and paste the following code in the btnTest_Click event:
    Try
       Dim myConnString As String = _
            "User ID=myUID;password=myPWD;Initial Catalog=pubs;Data Source=mySQLServer"
        Dim mySelectQuery As String = "SELECT * FROM Titles"
        Dim myConnection As New SqlConnection(myConnString)
        Dim myCommand As New SqlCommand(mySelectQuery, myConnection)
        myConnection.Open()
        Dim myReader As SqlDataReader = myCommand.ExecuteReader()
        While myReader.Read()
            'Process data.
        End While
        myReader.Close() 'Close the reader.
    
        myCommand.CommandText = "SELECT * FROM Sales"
        Dim myReader1 As SqlDataReader = myCommand.ExecuteReader()
        While myReader1.Read()
            'Process data.
        End While
        myReader1.Close() 'Close the reader.
    
        Dim myInsertQuery As String = "INSERT INTO Employee " & _
              "(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _
              "VALUES ('MSD12923F', 'JP', 'W', 'Mackenzie', " & _
              "10, 82,'0877','2001-01-01')"
        myCommand.CommandText = myInsertQuery
        myCommand.ExecuteNonQuery()
    
        'You can use the command any number of times.
    
        myConnection.Close()
    Catch ex As Exception
        MessageBox.Show(ex.ToString())
    End Try
    					
  6. Modify the connection string (myConnString) as appropriate for your environment.
  7. Save your project. On the Debug menu, click Start to run your project.
back to the top

Troubleshooting

  • While the SqlDataReader object is in use, the associated SqlConnection object serves the SqlDataReader, and you cannot perform any other operations on the SqlConnection object other than to close it. This is true until you call the Close method of the SqlDataReader object. This means, for example, that you cannot retrieve output parameters until after you call Close.For additional information about how to handle output parameters, click the article number below to view the article in the Microsoft Knowledge Base:

    308051 PRB: Output Parameters Are Not Returned When You Run an ADO.NET Command in Visual Basic .NET

  • If the method that runs a SqlCommand generates a SqlException exception, the SqlConnection remains open if the severity level is 19 or less. If the severity level is 20 or greater, the server usually closes the SqlConnection. However, you can reopen the connection and continue.
back to the top

REFERENCES

For additional information, click the article numbers below to view the articles in the Microsoft Knowledge Base:

313590 INFO: Roadmap for ADO.NET

313480 INFO: Roadmap for .NET Data Providers

309490 HOW TO: Handle Multiple Results by Using the DataReader in Visual Basic .NET

301075 HOW TO: Connect to a Database and Run a Command by Using ADO.NET and Visual Basic .NET

back to the top

Modification Type:MajorLast Reviewed:9/3/2003
Keywords:kbHOWTOmaster kbSqlClient kbSystemData KB317150 kbAudDeveloper