29
VB.Net VB.Net Database Database Access Access

VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

  • Upload
    vuminh

  • View
    255

  • Download
    0

Embed Size (px)

Citation preview

Page 1: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

VB.NetVB.NetDatabaseDatabaseAccessAccess

VB.NetVB.NetDatabaseDatabaseAccessAccess

Page 2: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

DatabasesDatabases• A comprehensive collection of related data organized for

convenient access, generally in a computer.• It is the collection of schemes, tables, queries,

reports, views and other objects. The data is typically organizedto model aspects of reality in a way thatsupports processes requiring information, such as modelling theavailability of rooms in hotels in a way that supports finding ahotel with vacancies.

• A database management system (DBMS) is a computersoftware application that interacts with the user, otherapplications, and the database itself to capture and analyzedata. A general-purpose DBMS is designed to allow thedefinition, creation, querying, update, and administration ofdatabases. Well-known DBMSsinclude MySQL, PostgreSQL,Microsoft SQLServer, Oracle, Sybase and IBM DB2.

• A comprehensive collection of related data organized forconvenient access, generally in a computer.

• It is the collection of schemes, tables, queries,reports, views and other objects. The data is typically organizedto model aspects of reality in a way thatsupports processes requiring information, such as modelling theavailability of rooms in hotels in a way that supports finding ahotel with vacancies.

• A database management system (DBMS) is a computersoftware application that interacts with the user, otherapplications, and the database itself to capture and analyzedata. A general-purpose DBMS is designed to allow thedefinition, creation, querying, update, and administration ofdatabases. Well-known DBMSsinclude MySQL, PostgreSQL,Microsoft SQLServer, Oracle, Sybase and IBM DB2.

Page 3: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and
Page 4: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

Connecting to theConnecting to theDatabaseDatabase

• Tools• Connect to Database• Microsoft SQL Server• Enter the Server Name• Choose authentication mode and enter credentials• Select or enter database name• Click on Test Connection (Should show “Test

Connection Succeeded”

• Tools• Connect to Database• Microsoft SQL Server• Enter the Server Name• Choose authentication mode and enter credentials• Select or enter database name• Click on Test Connection (Should show “Test

Connection Succeeded”

Page 5: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

• Applications communicate with a database, firstly,to retrieve the data stored there and present it in auser-friendly way, and secondly, to update thedatabase by inserting, modifying and deleting data.

• Microsoft ActiveX Data Objects.Net (ADO.Net) is apart of the .Net framework that is used by the .Netapplications for retrieving, accessing and updatingdata.

• We interact with database systems through SQLqueries or stored procedures.

• ADO.NET makes use of a local buffer of persistentdata called a data set.

• The application automatically connects to thedatabase server when it needs to run a query andthen disconnects immediately after getting the resultback and storing it in the dataset.

• Applications communicate with a database, firstly,to retrieve the data stored there and present it in auser-friendly way, and secondly, to update thedatabase by inserting, modifying and deleting data.

• Microsoft ActiveX Data Objects.Net (ADO.Net) is apart of the .Net framework that is used by the .Netapplications for retrieving, accessing and updatingdata.

• We interact with database systems through SQLqueries or stored procedures.

• ADO.NET makes use of a local buffer of persistentdata called a data set.

• The application automatically connects to thedatabase server when it needs to run a query andthen disconnects immediately after getting the resultback and storing it in the dataset.

Page 6: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

• It maintains a local repository of data in the datasetobject.

• The dataset object stores the tables, their relationshipsand their different constraints.

• The user can perform operations like update, insert anddelete on this local dataset.

• The changes made to the dataset are applied to theactual database as a batch when needed.

• This greatly reduces network traffic and results in betterperformance.

• It maintains a local repository of data in the datasetobject.

• The dataset object stores the tables, their relationshipsand their different constraints.

• The user can perform operations like update, insert anddelete on this local dataset.

• The changes made to the dataset are applied to theactual database as a batch when needed.

• This greatly reduces network traffic and results in betterperformance.

Page 7: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

• A .NET Framework data provider is used for connectingto a database, executing commands, and retrievingresults.

• Those results are either processed directly, placed in aDataSet in order to be exposed to the user as needed orcombined with data from multiple sources.

• There are different data providers for different types ofdatabases, such as .NET Framework Data Provider forSQL Server for Microsoft SQL Server.

• All of the generic classes for data access are containedin the System.Data namespace.

• A .NET Framework data provider is used for connectingto a database, executing commands, and retrievingresults.

• Those results are either processed directly, placed in aDataSet in order to be exposed to the user as needed orcombined with data from multiple sources.

• There are different data providers for different types ofdatabases, such as .NET Framework Data Provider forSQL Server for Microsoft SQL Server.

• All of the generic classes for data access are containedin the System.Data namespace.

Page 8: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and
Page 9: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

• The following table outlines the four core objectsthat make up a .NET Framework data provider:

Object Description

Connection Establishes a connection to a specific data source.

Executes a command against a data source. Exposes Parametersand can execute in the scope of a Transaction from aConnection.

CommandExecutes a command against a data source. Exposes Parametersand can execute in the scope of a Transaction from aConnection.

DataReader Reads a forward-only, read-only stream of data from a datasource.

DataAdapter Populates a DataSet and resolves updates with the data source.

Page 10: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

• The object model can be pictorially described as:

Page 11: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

• Data sets: Store data in a disconnected cache andthe application retrieves data from it.

• The dataset works as a virtual database containingtables, rows, and columns.

• When a connection is established with thedatabase, the data adapter creates a dataset andstores data in it.

• Data readers: Provide data access to theapplication in a read-only and forward-only mode.

• Data sets: Store data in a disconnected cache andthe application retrieves data from it.

• The dataset works as a virtual database containingtables, rows, and columns.

• When a connection is established with thedatabase, the data adapter creates a dataset andstores data in it.

• Data readers: Provide data access to theapplication in a read-only and forward-only mode.

Page 12: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

NET Framework Data Provider for SQLNET Framework Data Provider for SQLServer (SqlClient)Server (SqlClient)

• The .NET Framework Data Provider for SQL Server(SqlClient) uses its own protocol to communicate withSQL Server.

• The following statement shows how to include theSystem.Data.SqlClient namespace in your applications.

Imports System.Data.SqlClientImports System.Data.SqlClient

• The .NET Framework Data Provider for SQL Server(SqlClient) uses its own protocol to communicate withSQL Server.

• The following statement shows how to include theSystem.Data.SqlClient namespace in your applications.

Imports System.Data.SqlClientImports System.Data.SqlClient

Page 13: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

• DataTableCollectionIt contains all the tables retrieved from the data source.

• DataRelationCollectionIt contains relationships and the links between tables in a data set.

• DataTableIt represents a table in the DataTableCollection of a dataset. Itconsists of the DataRow and DataColumn objects. The DataTableobjects are case-sensitive.

• DataRelationIt represents a relationship in the DataRelationshipCollection of thedataset. It is used to relate two DataTable objects to each otherthrough the DataColumn objects.

• DataRowCollectionIt contains all the rows in a DataTable.

• DataViewIt represents a fixed customized view of a DataTable for sorting,filtering, searching, editing and navigation.

• DataColumnIt consists of the number of columns that comprise a DataTable.

• DataTableCollectionIt contains all the tables retrieved from the data source.

• DataRelationCollectionIt contains relationships and the links between tables in a data set.

• DataTableIt represents a table in the DataTableCollection of a dataset. Itconsists of the DataRow and DataColumn objects. The DataTableobjects are case-sensitive.

• DataRelationIt represents a relationship in the DataRelationshipCollection of thedataset. It is used to relate two DataTable objects to each otherthrough the DataColumn objects.

• DataRowCollectionIt contains all the rows in a DataTable.

• DataViewIt represents a fixed customized view of a DataTable for sorting,filtering, searching, editing and navigation.

• DataColumnIt consists of the number of columns that comprise a DataTable.

Page 14: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

Connecting to a Database• The .Net Framework provides the SqlConnection

class which is designed for connecting to MicrosoftSQL Server.

• The Oledb connection class: For connecting to awide range of databases such as Microsoft Accessand Oracle

Connecting to a Database• The .Net Framework provides the SqlConnection

class which is designed for connecting to MicrosoftSQL Server.

• The Oledb connection class: For connecting to awide range of databases such as Microsoft Accessand Oracle

Page 15: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

DataSetDataSet• DataSet is an in-memory representation of data.• It is a disconnected, cached set of records that are

retrieved from a database.• After the data is retrieved and stored in a dataset, the

connection with the database is closed.• This is called the 'disconnected architecture'.

• DataSet is an in-memory representation of data.• It is a disconnected, cached set of records that are

retrieved from a database.• After the data is retrieved and stored in a dataset, the

connection with the database is closed.• This is called the 'disconnected architecture'.

Page 16: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

Example: Read directly from SQL db usingExample: Read directly from SQL db using

dataSetdataSet

• Prerequisites:Microsoft SQL Server ExpressSQL Server Management Studio

1. Create a database called SQLApps2. Create a table called members, containing 2 or more

fields3. Insert 3 rows of data in your table4. Create the VB projects shown in the following slides

• Prerequisites:Microsoft SQL Server ExpressSQL Server Management Studio

1. Create a database called SQLApps2. Create a table called members, containing 2 or more

fields3. Insert 3 rows of data in your table4. Create the VB projects shown in the following slides

Page 17: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

• Start a new Windows form application,and call it SQLApp

• Right click on the solution explorer andadd a new class, and name itSQLControl

• The code for this class is on the next slide

• Start a new Windows form application,and call it SQLApp

• Right click on the solution explorer andadd a new class, and name itSQLControl

• The code for this class is on the next slide

Page 18: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

SQLControlSQLControl classclassImports System.Data.SqlImports System.Data.SqlClient

Public Class SQLControl'SQLCon is the connection, with the connection parametersPublic SQLCon As New SqlConnection With {.ConnectionString = "Data Source=IDEA-

PC\SQLEXPRESS;Initial Catalog=SQLApps;Persist Security Info=True;User ID=sa;Password=1234"}Public SQLCmd As SqlCommand ' Used for querying the DB after successfully connecting to

it

Public Function HasConnection() As Boolean 'Function to test the SQLCon if it successfullyopens and closesTry

SQLCon.Open()

SQLCon.Close()Return True

Catch ex As ExceptionMsgBox(ex.Message) 'A message box to explain why the error occuredReturn False

End TryEnd Function

End Class

Imports System.Data.SqlImports System.Data.SqlClient

Public Class SQLControl'SQLCon is the connection, with the connection parametersPublic SQLCon As New SqlConnection With {.ConnectionString = "Data Source=IDEA-

PC\SQLEXPRESS;Initial Catalog=SQLApps;Persist Security Info=True;User ID=sa;Password=1234"}Public SQLCmd As SqlCommand ' Used for querying the DB after successfully connecting to

it

Public Function HasConnection() As Boolean 'Function to test the SQLCon if it successfullyopens and closesTry

SQLCon.Open()

SQLCon.Close()Return True

Catch ex As ExceptionMsgBox(ex.Message) 'A message box to explain why the error occuredReturn False

End TryEnd Function

End Class

Page 19: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

Form1 ClassForm1 ClassPublic Class Form1

Dim SQL As New SQLControl ' A new instance of the class

Private Sub Form1_Load(ByVal sender AsSystem.Object, ByVal e As System.EventArgs) HandlesMyBase.Load

If SQL.HasConnection = True ThenMsgBox("Successfully Connected")

End IfEnd Sub

End Class

Public Class Form1Dim SQL As New SQLControl ' A new instance of the class

Private Sub Form1_Load(ByVal sender AsSystem.Object, ByVal e As System.EventArgs) HandlesMyBase.Load

If SQL.HasConnection = True ThenMsgBox("Successfully Connected")

End IfEnd Sub

End Class

Page 20: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

Reading data fromReading data fromDatabase using theDatabase using the

DataSetDataSet

Reading data fromReading data fromDatabase using theDatabase using the

DataSetDataSet

Page 21: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

SQLControlSQLControl classclassImports System.Data.SqlImports System.Data.SqlClient

Public Class SQLControlPublic SQLCon As New SqlConnection With

{.ConnectionString = "Data Source=IDEA-PC\SQLEXPRESS;InitialCatalog=SQLApps;Persist SecurityInfo=True;User ID=sa;Password=xxx"}

Public SQLCmd As SqlCommand

Public Function HasConnection() As BooleanTry

SQLCon.Open()

SQLCon.Close()Return True

Catch ex As ExceptionMsgBox(ex.Message)Return False

End TryEnd Function

Public Sub RunQuery(ByVal Query As String)

TrySQLCon.Open()SQLCmd = New SqlCommand(Query,

SQLCon)'Read directly from database using a

datareaderDim R As SqlDataReader =

SQLCmd.ExecuteReader

While R.ReadMsgBox(R.GetName(0) & ": " & R(0))

End While

SQLCon.Close()Catch ex As Exception

MsgBox(ex.Message)End Try

End SubEnd Class

Imports System.Data.SqlImports System.Data.SqlClient

Public Class SQLControlPublic SQLCon As New SqlConnection With

{.ConnectionString = "Data Source=IDEA-PC\SQLEXPRESS;InitialCatalog=SQLApps;Persist SecurityInfo=True;User ID=sa;Password=xxx"}

Public SQLCmd As SqlCommand

Public Function HasConnection() As BooleanTry

SQLCon.Open()

SQLCon.Close()Return True

Catch ex As ExceptionMsgBox(ex.Message)Return False

End TryEnd Function

Public Sub RunQuery(ByVal Query As String)

TrySQLCon.Open()SQLCmd = New SqlCommand(Query,

SQLCon)'Read directly from database using a

datareaderDim R As SqlDataReader =

SQLCmd.ExecuteReader

While R.ReadMsgBox(R.GetName(0) & ": " & R(0))

End While

SQLCon.Close()Catch ex As Exception

MsgBox(ex.Message)End Try

End SubEnd Class

Page 22: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

Form 1Form 1-- Contains a command button, aContains a command button, a

datagridviewdatagridview and the following codeand the following code

Public Class Form1Dim SQL As New SQLControl

Private Sub Button1_Click(ByVal sender AsSystem.Object, ByVal e As System.EventArgs)Handles Button1.Click

If SQL.HasConnection = True ThenSQL.RunQuery("SELECT Name from

members")End If

End SubEnd Class

Public Class Form1Dim SQL As New SQLControl

Private Sub Button1_Click(ByVal sender AsSystem.Object, ByVal e As System.EventArgs)Handles Button1.Click

If SQL.HasConnection = True ThenSQL.RunQuery("SELECT Name from

members")End If

End SubEnd Class

Page 23: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

NoteNote

• Before attempting to execute the code, aconnection has to be created to the database, anda connection string will automatically be generated.

• Before attempting to execute the code, aconnection has to be created to the database, anda connection string will automatically be generated.

Page 24: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

SummarySummaryModule

Declaration:• Command• Query

Running Query:Open connectionCreate command instance with parameters:

Execute reader, which executes the commandDisplay result

Module

Declaration:• Command• Query

Running Query:Open connectionCreate command instance with parameters:

Execute reader, which executes the commandDisplay result

Command

QueryString ConnectionString

Page 25: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

AlternativelyAlternatively

• We can use a SQL dataAdapter(DataProvider) tomake use of a dataset and populate it in adatagridview

Page 26: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

Form 1Form 1Public Class Form1

Dim SQL As New SQLControlPrivate Sub cmdQuery_Click_1(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles cmdQuery.Click

If SQL.HasConnection = True Then

SQL.RunQuery(txtQuery.Text)If SQL.SQLDataset.Tables.Count > 0 Then

DataGridView1.DataSource = SQL.SQLDataset.Tables(0)End If

Else

MsgBox("")

End IfEnd Sub

End Class

Public Class Form1Dim SQL As New SQLControlPrivate Sub cmdQuery_Click_1(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles cmdQuery.Click

If SQL.HasConnection = True Then

SQL.RunQuery(txtQuery.Text)If SQL.SQLDataset.Tables.Count > 0 Then

DataGridView1.DataSource = SQL.SQLDataset.Tables(0)End If

Else

MsgBox("")

End IfEnd Sub

End Class

Page 27: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

SQLcontrol.vb classSQLcontrol.vb classImports System.Data.SqlImports System.Data.SqlClient

Public Class SQLControlPublic SQLCon As New SqlConnection With

{.ConnectionString = "Data Source=IDEA-PC\SQLEXPRESS;InitialCatalog=SQLApps;Persist SecurityInfo=True;User ID=sa;Password=1234"}

Public SQLCmd As SqlCommandPublic SQLDA As SqlDataAdapterPublic SQLDataset As DataSet

Public Function HasConnection() As BooleanTry

SQLCon.Open()SQLCon.Close()Return True

Catch ex As ExceptionMsgBox(ex.Message)Return False

End TryEnd Function

Public Sub RunQuery(ByVal Query As String)

TrySQLCon.Open()SQLCmd = New SqlCommand(Query,

SQLCon)'LoadSQL Records for datagridSQLDA = New

SqlDataAdapter(SQLCmd)SQLDataset = New DataSetSQLDA.Fill(SQLDataset)SQLCon.Close()

Catch ex As ExceptionMsgBox(ex.Message)If SQLCon.State =

ConnectionState.Open ThenSQLCon.Close()

End IfEnd Try

End Sub

Imports System.Data.SqlImports System.Data.SqlClient

Public Class SQLControlPublic SQLCon As New SqlConnection With

{.ConnectionString = "Data Source=IDEA-PC\SQLEXPRESS;InitialCatalog=SQLApps;Persist SecurityInfo=True;User ID=sa;Password=1234"}

Public SQLCmd As SqlCommandPublic SQLDA As SqlDataAdapterPublic SQLDataset As DataSet

Public Function HasConnection() As BooleanTry

SQLCon.Open()SQLCon.Close()Return True

Catch ex As ExceptionMsgBox(ex.Message)Return False

End TryEnd Function

Public Sub RunQuery(ByVal Query As String)

TrySQLCon.Open()SQLCmd = New SqlCommand(Query,

SQLCon)'LoadSQL Records for datagridSQLDA = New

SqlDataAdapter(SQLCmd)SQLDataset = New DataSetSQLDA.Fill(SQLDataset)SQLCon.Close()

Catch ex As ExceptionMsgBox(ex.Message)If SQLCon.State =

ConnectionState.Open ThenSQLCon.Close()

End IfEnd Try

End Sub

Page 28: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

SummarySummary

Page 29: VB.Net Database Access - CUT · VB.Net Database Access. Databases • A comprehensive collection of related data organized for convenient access, generally in a computer. ... and

Assignment 2Assignment 2

• Create a hospital app for storing client details andviewing the details.

• Create a hospital app for storing client details andviewing the details.