Chapter 6

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 40

Mettu University

Event driven programming ITec3053

Chapter 6- Database Programming

30-12-2016
Outline

o The ADO.NET Architecture

o LINQ Architecture

o The .NET Data providers

o Working with the common .NET Data providers

o The Dataset Component

o Using the DataGridView for database access

30-12-2016
Database Concepts
o A database is a collection of one or more tables, each
containing data related to a particular topic.
o Visual Basic applications use database management
systems to make large amounts of data available to
programs.
o Visual Basic can interact with many DBMS’s

– Microsoft SQL Server

– Oracle

– MySQL
o Microsoft SQL Server 2008 Express used in this chapter
30-12-2016
Layered Approach to Using a DBMS

o Applications that work with a DBMS


use a layered approach
– VB application is topmost layer
– VB sends instructions to next
layer, the DBMS
– DBMS works directly with data
o Programmer need not understand the
physical structure of the data
– Just need to know how to interact
with the database

30-12-2016
Terminology

o Database: a collection of interrelated tables.

o Table: a logical grouping of related data.


– A category of people, places, or things
– For example, employees or departments
– Organized into rows and columns
o Field: an individual piece of data pertaining to an item, an
employee name for instance
o Record: the complete data about a single item such as all
information about an employee
– A record is a row of a table

30-12-2016
Database Table

o Each table has a primary key

– Uniquely identifies that row of the table


– Emp_Id is the primary key in this example
o Columns are also called fields or attributes
o Each column has a particular data type

30-12-2016
VB and SQL Server Data Types

o VB data types must match table data types.

o SQL Server and VB have similar data types


SQL Type Usage Visual Basic Type
Bit True/false values Boolean
DateTime Dates and times Date,
DateTime
Decimal, Money Financial values Decimal
Float Real-number values Double
Int Integer values Integer
Smallint Integers -32,768 to 32,767 Short
Varchar(n) Variable length strings String
Text Strings more than 8000 char String
30-12-2016
Choosing Column Names
o Define a column for each piece of data
o Allow plenty of space for text fields
o Avoid using spaces in column names
o For the members of an organization:
Column Name Type Remarks
Member_ID int Primary key
First_Name varchar(40)
Last_Name varchar(40)
Phone varchar(30)
Email varchar(50)
Date_Joined smalldatetime Date only, no time
values
Meeings_Attended smallint
Officer Yes/No True/False values

30-12-2016
One-to-Many Relationships

o The previous changes created a one-to-many relationship


– Every employee has one and only one dept
– Every department has many employees
– DeptID in department table is a primary key
– DeptID in employee table is a foreign key
o One-to-many relationship exists when primary key of one
table is specified as a field of another table.

30-12-2016
What is ADO.NET?

o A data-access technology that enables applications to


connect to data stores and manipulate data contained
in them in various ways.
o Former version was ADO (ActiveX Data Object)
o An object oriented framework that allows you to
interact with database systems.

30-12-2016
o What is the difference between ADO and ADO.Net
• ADO works with the connected data whereas ADO.Net works in
a disconnected manner.
• ADO has main object called Recordset which is used to
reference data. But ADO.Net has various objects to access the
database

30-12-2016
ADO.NET Architecture

30-12-2016
LINQ Architecture
o LINQ that stands for Language Integrated Query
(pronounced as “link”) is a .NET language extension that
supports data retrieval from different data sources like
XML document, databases and collections.
o It was introduced in the .NET 3.5 framework.
o VB and C# are the languages that have LINQ capabilities.
o Introduced in Visual Studio 2008 and designed by Anders
Hejlsberg.
• Allows writing queries even without the knowledge of
query languages like SQL, XML etc.
• LINQ queries can be written for diverse data types.

30-12-2016
LINQ Architecture…
o Example of a LINQ query
Module Module1
Sub Main()
Dim words As String() = {"hello", "wonderful", "LINQ", "beautiful", "world"}
' Get only short words
Dim shortWords = From word In words
Where word.Length <= 5
Select word
' Print each word out. Output
For Each word In shortWords hello
Console.WriteLine(word) LINQ
Next world
Console.ReadLine()
End Sub
End Module

30-12-2016
LINQ Architecture…

Syntax of LINQ
oThere are two syntaxes of LINQ. These are the following ones.
1.Lamda Method Syntax
oExample
var longWords = words.Where( w => w.length > 10);
Dim longWords = words.Where(Function(w) w.length > 10)
2.Query Comprehension Syntax
oExample
var longwords = from w in words where w.length > 10;
Dim longwords = from w in words where w.length > 10

30-12-2016
Types of LINQ
o The types of LINQ are mentioned below in brief.
1. LINQ to Objects:
o Allows querying in-memory objects like arrays, lists, generic list and any type of
collections.
2. LINQ to XMLXLINQ:
o Allows querying the XML document by converting the document into XElement
objects and then querying using the local execution engine.
3. LINQ to DataSet:
o Allows query to any database that can be queried with ADO.NET.
4.LINQ to SQL DLINQ:
o It’s specifically used to work with the SQL server database
5. LINQ to Entities:
o It is similar to LINQ to SQL. It allows developers to query the conceptual entity
data model

30-12-2016
LINQ Architecture in .NET
o LINQ has a 3-layered architecture in which the uppermost layer
consists of the language extensions and the bottom layer consists of
data sources.

30-12-2016
LINQ Architecture in .NET…

Need For LINQ


oPrior to LINQ, it was essential to learn C#, SQL, and various
APIs that bind together the both to form a complete
application.
oSince, these data sources and programming languages face
an impedance mismatch; a need of short coding is felt.
oBelow is an example of how many diverse techniques were
used by the developers while querying a data before the
advent of LINQ.

30-12-2016
LINQ Architecture in .NET…

SqlConnection sqlConnection = new SqlConnection(connectString);

SqlConnection.Open();

System .Data.SqlClient.SqlCom m and sqlCom m and = new SqlCom m


and();

sqlCom m and.Connection = sqlConnection;

sqlCom m and.Com m andText = "Select * from Customer";

return sqlCommand.ExecuteReader

(CommandBehavior.CloseConnection)

30-12-2016
LINQ Architecture in .NET…

o Using LINQ, the same data query can be written in a


readable form like the following one mentioned
below that too in a very less time.

Northwind db = new Northwind(@ "C:\Data\Northwnd.mdf");

var query = from c in db.Customers

select c;

30-12-2016
Advantages of LINQ

o LINQ offers syntax highlighting that proves helpful to find out


mistakes during design time.
o LINQ offers IntelliSense which means writing more accurate queries
easily.
o Writing codes is quite faster in LINQ and thus development time also
gets reduced significantly.
o Viewing relationship between two tables is easy with LINQ due to its
hierarchical feature and this enables composing queries joining
multiple tables in less time.

30-12-2016
Advantages of LINQ…

o LINQ allows usage of a single LINQ syntax while querying many diverse
data.
o LINQ is extensible that means it is possible to use knowledge of LINQ to
querying new data source types.
o LINQ offers the facility of joining several data sources in a single query
as well as breaking complex problems into a set of short queries easy to
debug.
o LINQ offers easy transformation for conversion of one data type to
another like transforming SQL data to XML data.

30-12-2016
The .NET Data providers

o Microsoft SQL Server

– Applications using SQL Server 7.0 or later

o Oracle

– Applications using Oracle data sources

o Object Linking and Embedding Database (OLE DB)

– Applications that use Microsoft Access databases

o Open Database Connectivity (ODBC)

– Applications supported by earlier versions of Visual Studio

30-12-2016
The .NET Data providers…

o Classes are encapsulated into a different namespace by


provider.

o Four core classes make up each data provider namespace

– Connection

– Command

– DataReader

– DataAdapter

30-12-2016
Working with the common .NET Data providers

ADO.NET Data Provider Namespace


.Net Framework Network provider

SQL Server System.Data.SqlClient

Oracle System.Data.OracleClient

Object Linking and Embedding Database(OLE System.Data.Oledb


DB)
Open Database Connectivity System.Data.Odbc

30-12-2016
Working with the common .NET Data providers

Object Description
Connection Allows establishing and releasing connections, and to begin
transactions
Command Executes a command against a data source. Often in the form of SQL
statements that retrieves data from the data source.
Data Reader Reads a forward-only, read-only stream of data from a data source
Data Adapter Populates a dataset and updates a database.

Data Set Represents a cache of data. Consists of a set of DataTables and


relations among them
DataTable Has a collection of DataRows and DataColumns representing table
  data, used in disconnected model

30-12-2016
Command Methods

o ExecuteReader() - Returns DataReader

o ExecuteNonQuery() - Returns # of Rows Affected

o ExecuteXMLReader() - Returns XMLReader Object to Read


XML documentation
o ExecuteScaler() - Returns a Single Value e.g. SQL SUM
function.

30-12-2016
The Dataset Component
o In-memory representation of data contained in a
database/XML
o Operations are performed on the DataSet, not the data source
o Can be created programmatically, using a DataAdapter or
XML schema and document (or any mixture)
Creating DataSets
Setup SqlConnection

Setup a SqlDataAdapter

Create a DataSet

Call the .Fill() method on the DA

30-12-2016
DataReader Vs. DataSet

Datareader Dataset

Forward only Loop through Dataset

Connected Recordset Disconnected Recordset

Single table involved Multiple tables involved

No relationship required Relationship between tables maintained

No XML storage Can be stored as XML

Occupies Less Memory Occupies More memory

Read only Can do addition / Updation and Deletion

30-12-2016
DataAdapters

o Pipeline between DataSets and data sources

o Supports select, insert, delete, update commands and methods

o Must always specify a select command

Using the DataAdapter

SQLDataAdapter sqlDA = new SqlDataAdapter();

sqlDA.SelectCommand =new SqlCommand ("select * from authors“,


sqlConnection);

DataSet sqlDS = new DataSet("authorsTable");

sqlDA.Fill(sqlDS, "authorsTable");

30-12-2016
DataTables

o A DataSet contains one or more DataTables.

o Fields are held within the DataTable.

o And in DataRows, DataColumns.


Using DataTables
o With a DataTable we can
• Insert, modify and update
• Search
• Apply views
• Compare
• Clear
• Copy

30-12-2016
DataRelations

o New to ADO.Net

o Tables within a DataSet can now have relationships, with integrity.

o Supports cascading updates and deletes.

DataViews
o Like a SQL view
o Single, or multiple tables
o Normally used with GUI applications via Data Binding.

30-12-2016
Using the DataGridView for database access

o Placeholder control for displaying data on form

– DataGridView is new to .NET Framework 2.0

– To instantiate DataGridView control, drag a table from Data Sources


window to form
o Specify how data is formatted and displayed

– DataGridView – Customizable table that allows you to modify columns, rows,


and borders
• Freeze rows and columns for scrolling purposes

• Hide rows or columns

• Provide ToolTips and shortcut menus

30-12-2016
How to connect VB.Net to SQL Server
o Here is the step by step procedure to connect vb.net to SQL server.
1. Create your VB.NET project
2. Include the following namespace
Imports System.Data
Imports System.Data.SqlClient
o The System.Data namespace provides access to classes that represent
the ADO.Net architecture.
o The System.Data.SqlClient namespace is the .Net framework data
provider for Sql server.
3. Declare and instantiate your Sql connection object as shown below
Dim con As New SqlConnection

30-12-2016
How to connect VB.Net to SQL Server…

4. Pass the SQL connection String to ConnectionString property of your


Sql Connection object.
con.ConnectionString = ("Data Source=(local);Initial
Catalog=registrar;Integrated Security=True")
oThe connectionstring value usually contains the following:
Data Source - physical server hostname
Initial catalog - your database name
5. Last step is to invoke he open method of the connection
object
Dim con As New SqlConnection
Dim cmd As New SqlCommand

30-12-2016
How to insert data to SQL Server…
Try
con.ConnectionString = ("Data Source=(local);Initial Catalog=registrar;Integrated Security=True")
con.Open()
cmd.Connection = con
cmd.CommandText = "insert into table([field1],[field2])VALUES([Value1],[Value2]) "
cmd.ExecuteNonQuery()
MsgBox("data is successfully inserted into database")
Catch ex As Exception
MessageBox.Show("the value is not properly entered into the database" & ex.Message, "insert")
Finally
con.Close()
End Try

End Try

30-12-2016
How to connect VB.Net to SQL Server…

o How to delete record on SQL database


Dim con As SqlConnection
Dim cmd As New SqlCommand
Try
Dim con As SqlConnection = New SqlConnection("Data Source=(local);Initial
Catalog=registrar;Integrated Security=True")
con.Open()
Dim sql As String = “Delete From table_Name Where field1 =‘test’”
Dim cmd As SqlCommand = New SqlCommand(sql, con)
cmd.ExecuteNonQuery()
con.Close()
MessageBox.Show("This student is deleted succesfully")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

30-12-2016
How to connect VB.Net to SQL Server…
o How to update record on SQL database
Dim con As SqlConnection
Dim cmd As New SqlCommand
Try
Dim con As SqlConnection = New SqlConnection("Data Source=(local);Initial
Catalog=registrar;Integrated Security=True")
con.Open()
cmd.Connection=con
cmd.CommandText=“UPDATE table SET field1=Value1,field2=Value2 where field3=‘Test’”
cmd.ExecuteNonQuery()
MessageBox.Show("This record is updated succesfully")
Catch ex As ExceptionessageBox.Show(“Error while Updating record on table…” &ex.Message
“update Records”)
Finally
con.Close()
End Try

30-12-2016
How to connect VB.Net to SQL Server…

o How to Search record from SQL Database


Dim con As SqlConnection
Dim cmd As New SqlCommand
Try
Dim con As SqlConnection = New SqlConnection("Data Source=(local);Initial Catalog=registrar;Integrated Security=True")
con.Open()
Dim sql As String = "select * from table_name where field='" & TextBox5.Text & "'"
Dim cmd As SqlCommand = New SqlCommand(sql, CON)
Dim dr As SqlDataReader
dr = cmd.ExecuteReader()
If (dr.HasRows) Then
While (dr.Read)
TextBox4.Text = dr(0)
TextBox6.Text = dr(1)
ElseIf TextBox1.Text = "" Then
MsgBox(“please first enter what you want to search ")
Else
MsgBox(“the record esn't exist in the database")
End If
Catch ex As Exception
MessageBox.Show("this record is doesn't exist in the database")
End Try
End While

30-12-2016
Thank You
End of Class
December 30,2016

30-12-2016

You might also like