How to connect to a database and run a command by using ADO.NET and Visual Basic .NET
How to connect to a database and run a command by using ADO.NET and Visual Basic .NET
This article was previously published under Q301075
For a Microsoft Visual C# .NET version of this
article, see
306636.
For a Microsoft Visual J# .NET version of this article, see 322045.
This article refers to the following Microsoft .NET Framework Class Library namespaces:
For a Microsoft Visual J# .NET version of this article, see 322045.
For a Microsoft Visual Basic 6.0 version of this
article, see
168336.
This article refers to the following Microsoft .NET Framework Class Library namespaces:
- System.Data
- System.Data.SqlClientHow to connect to a database and run a command by using ADO.NET and Visual Basic .NET
IN THIS TASK
Summary
Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:- Microsoft Windows XP, Microsoft Windows Server 2003, Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows NT 4.0 Server
- Microsoft Visual Studio .NET
- Database terminology
- Structured Query Language (SQL)
How to run a command
Commands are issued against databases to take actions against data stores and to include any statement that can be issued against a database. You can use the OleDbCommand or the SqlCommand classes to get a command to your data store, and OleDbCommand can be specific to the data store. This article demonstrates both the SqlClient class (to connect to a computer that is running Microsoft SQL Server) and the OleDb class (for any database that has an OLE DB or ODBC driver available) within ADO.NET. However, the code is generally the same for both.With ADO, you can issue commands through the Command, the Connection, or the Recordset object. In ADO.NET, only the Command objects (SqlCommand or OleDbCommand) run commands.
To run a command, follow these steps:
- Follow these steps to create a new console application in
Visual Basic .NET:
- Start Visual Studio .NET.
- On the File menu, point to New, and then click Project.
- In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Console Application under Templates.
- Make sure that your project contains a reference to the System.Data namespace, and add a reference if it does not.
- Use the Imports statement on the System and System.Data namespaces so that you do not have to qualify declarations in
those namespaces later in your code. You can also include System.Data.SqlClient or System.Data.OleDb, depending on which one you are using.
Imports System Imports System.Data Imports System.Data.SqlClient
- Before you can create a connection to a database, you must
have a connection string. Connection strings contain all of the information
that you need to establish a database connection, including the server name,
the database name, the user ID, and the password. For example, the following
connection string points to a local computer that is running SQL Server with a
strong password for the <username>
account:
For OleDb connections:Provider=SQLOLEDB.1;User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data Source=(local)
User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data Source=(local)
- Visual Studio creates a module and an empty Main() procedure. Declare a string variable, and store the appropriate
connection string for your database in this procedure:
Sub Main() Dim sConnectionString As String _ = "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data Source=(local)" End Sub
- Using this connection string, create a new OleDbConnection or SqlConnection object, and call its Open method to establish a connection to your database:
Dim objConn As New SqlConnection(sConnectionString) objConn.Open()
- Create a SqlCommand or OleDbCommand object, and pass in the command that you want to run and the
connection object that you created in the previous step. The following sample
code passes in the INSERT statement:
Dim sSQL As String = "INSERT INTO Employee " & _ "(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _ "VALUES ('MSD12923F', 'Duncan', 'W', 'Mackenzie', " & _ "10, 82,'0877','2001-01-01')" Dim objCmd As New SqlCommand(sSQL, objConn)
- After you create the SqlCommand or the OleDbCommand object, you can call the ExecuteNonQuery method to run the command that it represents. ExecuteNonQuery is designed for commands that do not return any results (such as
the DELETE, the UPDATE, and the INSERT statements). If the Execute statement runs without throwing an exception (see the following
code), the command has been executed successfully against the database.
objCmd.ExecuteNonQuery()
- Save your project. On the Debug menu, click Start to run your command against the database.
How to use parameters
When you run commands against a database (such as the UPDATE, the INSERT, and the DELETE statements or calls to stored procedures), these commands are frequently parameterized. This allows the command to be created one time but executed multiple times with different values that are inserted instead of parameters. Consider the corresponding DELETE statement to the INSERT statement that is used in the previous section:
Dim sSQL As String = "DELETE FROM Employee WHERE emp_id = @emp_id"
To use parameters with your command, follow these steps:
- Create your OleDbConnection or SqlConnection object, as you did in the "How to Run a Command" section.
- Replace the values with placeholders (for example, "@emp_id" or "@fname") so that your command text uses parameters. See the DELETE statement before these steps for an example.
- Create your OleDbCommand or SqlCommand object, and pass in the connection object that you created in the first step and the command text that contains the parameter placeholders.
- For each parameter, add a parameter object to the command
object's parameters collection. For each parameter, you must specify a name and
data type.
objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9)
- Stored procedures can have parameters that return values
and output parameters. You must also set a value for each input parameter
before you can run the query:
objCmd.Parameters.Item("@emp_id").Value = "MSD12923F"
- Run the query as follows:
Try objCmd.ExecuteNonQuery() Console.WriteLine("Record Deleted") Catch e As Exception Console.WriteLine(e.ToString) End Try Console.WriteLine("Record Deleted") Console.Read()
Complete code listing
Imports System
Imports System.Data
Imports System.Data.SqlClient
Module Module1
Sub Main()
AddRecord()
RemoveRecord()
Pause()
End Sub
Sub Pause()
Console.WriteLine("Press Enter To Continue...")
Console.ReadLine()
End Sub
Sub AddRecord()
Dim sConnectionString As String _
= "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data Source=(local)"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim sSQL As String = "INSERT INTO Employee " & _
"(emp_id, fname, minit, lname, job_id, job_lvl, pub_id, hire_date)" & _
"VALUES ('MSD12923F', 'Duncan', 'W', 'Mackenzie', " & _
"10, 82,'0877','2001-01-01')"
Dim objCmd As New SqlCommand(sSQL, objConn)
Try
objCmd.ExecuteNonQuery()
Catch e As Exception
Console.WriteLine(e.Message)
End Try
Console.WriteLine("Record Added")
End Sub
Sub RemoveRecord()
Dim sConnectionString As String _
= "User ID=<username>;Password=<strong password>;Initial Catalog=pubs;Data Source=(local)"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim sSQL As String = "DELETE FROM Employee WHERE emp_id = @emp_id"
Dim objCmd As New SqlCommand(sSQL, objConn)
objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9)
objCmd.Parameters.Item("@emp_id").Value = "MSD12923F"
Try
objCmd.ExecuteNonQuery()
Console.WriteLine("Record Deleted")
Catch e As Exception
Console.WriteLine(e.ToString)
End Try
Console.WriteLine("Record Deleted")
Console.ReadLine()
End Sub
End Module
References
SQL Server 2000 Stored Procedures
http://msdn.microsoft.com/en-us/library/aa174792.aspx
"Revisiting the Use of ADO in .NET Applications," MSDN Voices column
http://msdn.microsoft.com/en-us/library/ms810295.aspx
ADO.NET for the ADO Programmer
http://msdn.microsoft.com/en-us/library/ms973217.aspx
MSDN Online .NET Developer Center
http://msdn.microsoft.com/en-us/netframework/default.aspx
http://msdn.microsoft.com/en-us/library/aa174792.aspx
"Revisiting the Use of ADO in .NET Applications," MSDN Voices column
http://msdn.microsoft.com/en-us/library/ms810295.aspx
ADO.NET for the ADO Programmer
http://msdn.microsoft.com/en-us/library/ms973217.aspx
MSDN Online .NET Developer Center
http://msdn.microsoft.com/en-us/netframework/default.aspx
Properties
Article ID: 301075 - Last Review: 10/15/2012 09:41:00 - Revision: 5.0
- Microsoft ADO.NET 1.1
- Microsoft Visual Basic .NET 2003 Standard Edition
- Microsoft Visual Basic .NET 2002 Standard Edition
- kbhowtomaster KB301075
Comments
Post a Comment