Sunteți pe pagina 1din 7

Visual Basic.

NET Notes

Page 1 of 7

VB.NET Database Applications

Introduction to ADO.NET Data processing has traditionally relied primarily on a connection-based, two-tier model. As data processing increasingly uses multi-tier architectures, programmers are switching to a disconnected approach to provide better scalability for their applications. ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well as data sources exposed through OLE DB and XML. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data. ADO.NET cleanly factors data access from data manipulation into discrete components that can be used separately or in tandem. ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet object in order to be exposed to the user in an ad-hoc manner, combined with data from multiple sources, or remote between tiers. The ADO.NET DataSet object can also be used independently of a .NET Framework data provider to manage data local to the application or sourced from XML. ADO.NET Architecture

Source: ADO.NET contains the following components: Connection object provides connectivity to a data source. A data source may be a database, a text file, an object, a web service or a spreadsheet which contains data.

______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

Visual Basic.NET Notes

Page 2 of 7

Command object enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information. DataReader provides a high-performance stream of data from the data source. DataAdapter provides the bridge between the DataSet object and the data source. It uses Command objects to execute SQL commands at the data source to both load DataSet with data, and reconcile changes made to the data in the DataSet back to the data source.

In order to work with ADO.NET components in your application, you are required to import the System.Data namespaces. A namespace is a collection of built in classes where the functionalities are already defined. Data Providers Data Provider for SQL Server Data Provider for OLE DB Data Provider for ODBC Data Provider for Oracle Description For Microsoft SQL Server version 7.0 or later. For data sources exposed using OLE DB. For data sources exposed using ODBC. For Oracle data sources

Setting up a Connection You have to determine which data source you are using before setting the connection. This is because each connection requires you to specify the data provider to be used. In general, the data connection is declared as: Dim conn As Connection conn = New Connection(<data provider>, <data source>, <security info>) Note: Both statements can be combined (see Tutorial 1) Types of Connection String Access 2003 and below
Provider=Microsoft. Jet.OLEDB.4.0; Data Source=myAccess2007file.mdb; Persist Security Info=False;

Access 2007 and above

Provider=Microsoft.ACE.OLEDB.12.0; Data Source=myAccess2007file.accdb; Persist Security Info=False;

______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

Visual Basic.NET Notes

Page 3 of 7

SQL Server 2008

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Connection via IP Address (over a network)

Data Source=,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;

Tutorial 1: Creating a Login Form Design the following Windows Form. Ensure that you have a database call StudentsDB created with one table call Users which will contain two data fields, username and password. We will be using Access 2007 / 2010 database for this purpose.

Make changes to the password field TextBox so that the password characters are masked when users type their password. To make the changes, there are two optional properties that you can use. If you want to define you own password character then change PasswordChar property. For example, to change the masked password to use * (asterisk) symbol for each character, type the * on the property field.

Enter * here

Another way is to set the UseSystemPassword property of the TextBox to True. Note: Make sure you use either one only. If you have define the PasswordChar property make sure to clear the property value before setting the UseSystemPassword. Otherwise, the TextBox will only use the value in the PasswordChar property.
______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

Visual Basic.NET Notes

Page 4 of 7

Ok, let us make put the Login Form to work. 1. Type the namespace on the line before Public Class statement. Imports System.Data.OleDb This will enable you to access to the classes and functions of OLEDB. 2. Then enter the following class level variables and objects Dim Dim Dim Dim 3. cmd As OleDbCommand dr As OleDbDataReader da As New OleDbDataAdapter sql As String

Then create the connection string. Dim conn As OleDbConnection = _ New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=StudentsDB.accdb")


Next open the connection to the database and set the SQL statement for the login query. conn.Open() sql = "Select * From Users WHERE Username='" & txtUsr.Text & "' AND Password='" & txtPwd.Text & "'" The SQL query will return any matching using name and password from the Users table later when the query is executed by the command object.


Then create the command object by providing the SQL query and the connection string. cmd = New OleDbCommand(sql, conn) 'set the command object dr = cmd.ExecuteReader ' execute the reader


The application now needs to check whether there is a match with the entered username and password with the record in the database. This is achieved by comparing the values entered against those records retrieved by the command object. If there is a match, then it will return a True. If dr.HasRows = True Then MessageBox.Show("You have logged in successfully", "Login Success", MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("Incorrect username or password. Please retry.", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

Visual Basic.NET Notes

Page 5 of 7

txtUsr.Focus() End If

______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

Visual Basic.NET Notes

Page 6 of 7


Lastly, close the connection of the reader and the connection string. dr.Close() conn.Close()

Notes about the SQL statement used in the application SELECT statement The SQL SELECT statement is used for selecting (search) data from a database. The general SELECT syntax: SELECT datafield_names FROM table_name and SELECT * FROM table_name
The * is used to indicate all data fields in the table.

WHERE clause The WHERE clause in the SELECT statement is used for indicating a filter condition. The general syntax: SELECT datafield_names FROM table_name WHERE datafield_name operator value The datafield name in the WHERE clause indicating the data field to be used as filter, and the operator may include the following:
Operator = <> > < >= <= BETWEEN LIKE IN Description Equal Not equal Greater than Less than Greater than or equal Less than or equal Between an inclusive range Search for a pattern If you know the exact value you want to return for at least one of the columns

______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

Visual Basic.NET Notes

Page 7 of 7

The value is the value to be compared against in the clause. Example, if you are to search for all records of students whose home city is from Selangor, then the SQL query would be written as: SELECT * FROM Students WHERE City='Selangor' The enclosed single quotes is to denote a string value in SQL syntax. In the application above, the SQL query "Select * From Users WHERE Username='" & txtUsr.Text & "' AND Password='" & txtPwd.Text & "'" uses the AND logical operator to join two conditions, the username and the password fields in the WHERE clause. This would ensure that only an exact match of both the username and password values would be retrieved. Next Topic: Searching - By one data field and displaying individual record on textboxes, etc. - By selected field, and displaying the result on a data grid view.

______________________________________________________________________________________________ Asia Pacific Institute of Information Technology