VB.NetVB.NetDatabaseDatabaseAccessAccess
VB.NetVB.NetDatabaseDatabaseAccessAccess
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.
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”
• 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.
• 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.
• 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.
• 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.
• The object model can be pictorially described as:
• 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.
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
• 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.
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
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'.
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
• 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
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
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
Reading data fromReading data fromDatabase using theDatabase using the
DataSetDataSet
Reading data fromReading data fromDatabase using theDatabase using the
DataSetDataSet
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
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
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.
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
AlternativelyAlternatively
• We can use a SQL dataAdapter(DataProvider) tomake use of a dataset and populate it in adatagridview
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
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
SummarySummary
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.
Top Related