Visual Basic Database Tutorial
When programming in Visual Basic (VB), it's important to understand how to connect and query a database server. Database servers are the central components for dynamic content, and they are also responsible for serving data to client desktop applications such as customer management systems. Microsoft Visual Studio and .NET come with classes that enable the programmer to query a database using only a few lines of code.
-
Connection
-
The first part of querying the database in VB.NET is creating a connection. The connection is used to open a communication line to the database server. This connection is then used to send queries to the server. These queries can be any type of SQL statement. Below is an example of a database connection in VB.NET:
Dim myconnection As New SqlConnection("Initial Catalog = Northwind; Data Source=mySQLServer; User ID=username; password = myPassword; Connect Timeout=20")
myconnection.Open()The first line of code creates the SQL connection. Required in the connection is the name of the database, which is specified as "Initial Catalog." The "Data Source" variable is the server's name or IP address on the network. Finally, the username and password is also passed to authenticate the application. Even though the connection is opened, it is not actually connected, which is why the second line of code is entered. Once the connection is opened, the application can then make calls to the database.
Sending a Query to the Database
-
After creating the connection, queries can be sent to the database server. The following is the syntax used to create a query and assign it to a reader. A reader is a component that is used to print results back to the application. VB.NET is packaged with classes that already have readers defined:
Dim myCom As New SqlCommand("SELECT first_name from customers", myconnection )
Dim sqlReader As SqlDataReader = myCom.ExecuteReader( )The first line of code is the command. This command is set to a select query that retrieves the first names of customers in the database. Notice one of the parameters is the "myconnection" object defined in Section 1. This parameter is required so the command knows how to contact the server. The second line of code is the reader that is assigned the records returned from the command. The example below uses the reader to print the first record to the user's screen:
Console.WriteLine(sqlReader.GetSqlValue(1))
-
Related Searches
References
Comments
-
Michael Francisco
Jan 05, 2011
how to connect or network database in VB6.0?