Short Notes VBN - Database Part 1

Embed Size (px)

Citation preview

  • 7/29/2019 Short Notes VBN - Database Part 1

    1/7

    Visual Basic.NET Notes Page 1 of 7

    ______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

    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 adisconnected approach to provide better scalability for their applications.

    ADO.NET provides consistent access to data sources such as Microsoft SQL Server, as well asdata sources exposed through OLE DB and XML. Data-sharing consumer applications can useADO.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 inan ad-hoc manner, combined with data from multiple sources, or remote between tiers. TheADO.NET DataSet object can also be used independently of a .NET Framework data provider tomanage data local to the application or sourced from XML.

    ADO.NET Architecture

    Source: http://msdn.microsoft.com/en-us/library/27y4ybxw(v=vs.71).aspx

    ADO.NET contains the following components:

    Connection object provides connectivity to a data source. A data source may be adatabase, a text file, an object, a web service or a spreadsheet which contains data.

    http://msdn.microsoft.com/en-us/library/27y4ybxw(v=vs.71).aspxhttp://msdn.microsoft.com/en-us/library/27y4ybxw(v=vs.71).aspxhttp://msdn.microsoft.com/en-us/library/27y4ybxw(v=vs.71).aspxhttp://msdn.microsoft.com/en-us/library/27y4ybxw(v=vs.71).aspx
  • 7/29/2019 Short Notes VBN - Database Part 1

    2/7

    Visual Basic.NET Notes Page 2 of 7

    ______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

    Command object enables access to database commands to return data, modify data, runstored 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 loadDataSet with data, and reconcile changes made to the data in the DataSet back to the datasource.

    In order to work with ADO.NET components in your application, you are required to import theSystem.Data namespaces. A namespace is a collection of built in classes where thefunctionalities are already defined.

    Data Providers Description

    Data Provider for SQL Server For Microsoft SQL Server version 7.0 or later.Data Provider for OLE DB For data sources exposed using OLE DB.Data Provider for ODBC For data sources exposed using ODBC.Data Provider for Oracle 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 dataconnection is declared as:

    Dim conn As Connectionconn = New Connection(, , )

    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; PersistSecurity Info =False;

    Access 2007 and above

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

  • 7/29/2019 Short Notes VBN - Database Part 1

    3/7

    Visual Basic.NET Notes Page 3 of 7

    ______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

    SQL Server 2008

    Data Source =myServerAddress; Initial Catalog =myDataBase; UserId =myUsername; Password =myPassword;

    Connection via IP Address (over a network)

    Data Source =190.190.200.100,1433; Network Library =DBMSSOCN; InitialCatalog =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 createdwith one table call Users which will contain two data fields, username and password . We will beusing Access 2007 / 2010 database for this purpose.

    Make changes to the password field TextBox so that the password characters are masked whenusers type their password. To make the changes, there are two optional properties that you canuse. 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.

    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 makesure to clear the property value before setting the UseSystemPassword . Otherwise, the TextBoxwill only use the value in the PasswordChar property.

    Enter * here

  • 7/29/2019 Short Notes VBN - Database Part 1

    4/7

    Visual Basic.NET Notes Page 4 of 7

    ______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

    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 cmd As OleDbCommandDim dr As OleDbDataReaderDim da As New OleDbDataAdapterDim sql As String

    3. Then create the connection string.

    Dim conn As OleDbConnection = _New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=StudentsDB.accdb")

    4. 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.5. Then create the command object by providing the SQL query and the connection string.

    cmd = New OleDbCommand(sql, conn) 'set the command objectdr = cmd.ExecuteReader ' execute the reader

    6. The application now needs to check whether there is a match with the entered usernameand password with the record in the database. This is achieved by comparing the valuesentered against those records retrieved by the command object. If there is a match, then itwill return a True.

    If dr.HasRows = True ThenMessageBox.Show("You have logged in successfully","Login Success", MessageBoxButtons.OK,MessageBoxIcon.Information)

    ElseMessageBox.Show("Incorrect username or password. Pleaseretry.", "Login Failed", MessageBoxButtons.OK,MessageBoxIcon.Exclamation)

  • 7/29/2019 Short Notes VBN - Database Part 1

    5/7

    Visual Basic.NET Notes Page 5 of 7

    ______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

    txtUsr.Focus()End If

  • 7/29/2019 Short Notes VBN - Database Part 1

    6/7

    Visual Basic.NET Notes Page 6 of 7

    ______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

    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_namesFROM table_name

    and

    SELECT * FROM table_name

    The * is used to indicate all data fields in the table.

    WHERE clauseThe WHERE clause in the SELECT statement is used for indicating a filter condition. Thegeneral syntax:

    SELECT datafield_namesFROM table_name

    WHERE datafield_name operator value

    The datafield name in the WHERE clause indicating the data field to be used as filter, and theoperator may include the following:

    Operator Description= Equal Not equal> Greater than< Less than>= Greater than or equal

  • 7/29/2019 Short Notes VBN - Database Part 1

    7/7

    Visual Basic.NET Notes Page 7 of 7

    ______________________________________________________________________________________________ Asia Pacific Institute of Information Technology

    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, thenthe 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 & "' ANDPassword='" & txtPwd.Text & "'"

    uses the AND logical operator to join two conditions, the username and the password fields inthe WHERE clause.

    This would ensure that only an exact match of both the username and password values would beretrieved.

    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.