Pages

Monday, August 19, 2013

VB.NET SQL Database Tutorial

VB.NET SQL Database Tutorial

The .NET framework contains VB.NET and C language to provide developers with the tools to create dynamic Web and desktop applications. The VB.NET language is based on Visual Basic, and it is used to retrieve data from a database. The VB.NET developer can retrieve information from databases such as SQL Server, MySQL and Oracle. Retrieving data from a SQL Server includes setting up the connection, querying a table and displaying it to your readers.

Instructions

    1

    Create your SQL Server connection string. The connection string contains the SQL Server name, database you want to query and a user name and password. The information is stored in a connection object, which is later used to send the query command to the database. The following code sets up your connection string and variable:

    Dim conn As SqlConnection
    conn = New SqlConnection("server=database_server_name;uid=user;pwd=password;database=the_database")

    Replace "database_server_name" with the name of the SQL Server that hosts your database. The "the_database" value is the name of the database to query. The "uid" and "pwd" properties contain the user name and password that has permission to query the server.

    2

    Create your SQL Server command. This can be any query that retrieves, deletes or edits records in the table. In this example, customer records are retrieved where the customer ID is 1. The following code sets up an command variable:

    Dim command As SqlCommand
    command = New SqlCommand("Select first_name from customer were id=1", conn)

    3

    Open the database connection and execute the SQL query. The query returns a list of records, and these records also need a variable to contain them. A "SQL Reader" object is used to contain the returned records. The following code shows you how to retrieve records from the database:

    conn.Open()
    Dim reader As SqlDataReader()
    reader = command.ExecuteReader()

    4

    Print records for your user to view. You can print one or several records for the reader. The following code prints the first records to the screen:

    Response.Write(reader(0).ToString())

0 comments:

Post a Comment