visual programming · 6/9/2010 · support in ado .net for any data source for which there is an...
TRANSCRIPT
CBVP2103
Database is a collection of data that is stored by category. The categories are linked by the type of data stored. Database is also defined as a collection of data about related entities. Its application is to assist the process of collecting, storing and accessing data effectively.
A database is a collection of information. This information is stored in a very structured manner. By exploiting this known structure, we can access and modify the information quickly and correctly.
A table is a rectangular array of data.
Each column of the table is called a field.
Each row, called a record, contains the same type of information as every other row.
Database Management System (DBMS) is a system that exists specifically to manage the database.
DBMS makes sure that the data entered into the database can be viewed, manipulated, opened and accessed easily. There are many programming languages that are developed along with DBMS. Among them are Informix and Oracle.
DBMS has many advantages. Among them are:◦ Data is easily viewed by user;◦ Easy to access; and
◦ Easily manipulated by the user to generate information using SQL instructions.
DBMS such as Informix has three main interfaces for users:◦ Run SQL language;◦ Choose attributes in table through menu; and◦ Write programs that involve data from the
database.
There are many types of DBMS. However, the best and most often used are Relational DBMS. This type of DBMS separates data into categories that are named entities. An entity has attributes which is data that comprise of data name and value (attribute name and value).
Each entity needs the same attribute as other entities in order for a link to be established between the entities. For example, one entity called EMPLOYEE will contain the attribute name NAME, STAFFNO, ADDRESS. The next entity called POSITION will have the following attribute names, STAFFNO, GROSSSALARY, and CATEGORY.
ODBC: Open Database Connectivity◦ A driver manager◦ Used for relational databases
OLE DB: The OLE database protocol◦ Allows a program to access information in many
types of data source.◦ Data provider: databases, spreadsheets, etc.
ADO.NET: ActiveX Data Objects◦ An Interface for OLE DB.◦ Allow programmers to use a standard set of
objects to refer to any OLE DB data source.
.Net Applications
OLE DBProvider
OLE DBData Source
OLE DBProvider
ODBC
ODBCData Source
SQL Server Data Source
SQL Server .Net Data Provider
OLE DB .Net Data Provider
ADO.Net
One of the advantages of DBMS is that it supports SQL. SQL is an important language that is based on links. It is a command to the DBMS to give out information based on manipulation of data in the DBMS. SQL is a very powerful language. One use of SQL is to request specialized information from an existing database or to have the information presented in a specified order. Example:
Select * From EMPLOYEE
A Microsoft Access database file, which has an extension of mdb, contains tables, queries, forms, reports, pages, macros, and modules, which are referred to as database objects. That’s a lot of information in one large file, but Microsoft Access manages this data quite nicely. Forms, reports, pages, macros, and modules are generally concerned with letting users work with and display data. You will be writing Visual Basic 2005 applications to do this, so the only database objects you’re really concerned about at the moment are tables and queries.
The .NET data provider is the layer between the application and is designed for fast, efficient means of data retrieval and reconciliation.
Three types of Data Providers◦ SQL Server data provider
◦ OLEDB data provider
◦ ODBC Data Provider
SQL Server Data provider is the most efficient way to connect to an SQL Server Database
Manages the connection to a database
Executes a query commandon the database
Exchanges data between the data set and the database
Provides efficient access to astream of read-only data
Database
Connection
Command
DataReader
DataAdapter
The OleDb (Object Linking and Embedding Database) objects in System.Data.dll provide support in ADO .NET for any data source for which there is an OLE DB data provider. One in particular - ODBC - can be very useful for a lot of older data sources. Because there is an OLE DB provider that wraps ODBC, ADO .NET can work with virtually all legacy data.
ADO .NET is a collection of classes, interfaces, structures, and enumerated types that manage data access from relational data stores within the .NET Framework These collections are organized into namespaces:
System.Data,
System.Data.OleDb,
System.Data.SqlClient, etc.
ADO .NET is an evolution from ADO. Does not share the same object model, but shares
many of the same paradigms and functionality!
Connection Object: Represent a connection to the database.
Command Object: The command object allows us to execute a SQL statement or a stored procedure.
DataReader: It is a read-only and forward-only pointer into a table to retrieve records.
DataSet Object: A DataSet object can hold several tables and relationships between tables.
DataAdapter: This the object used to pass data between the database and the dataset.
Ap
plicati
on
OD
BC
Dri
ver
ODBCRDBMSO
DBC
OLE DBRDBMS
.NET Data Provider
Connection
Command
Data Reader
Data Adapter
OLE D
B
OLE D
B P
rovid
er
SQL Server
DataReader objects are highly optimised for fast, forward only enumeration of data from a data command
A DataReader is not disconnected
Access to data is on a per record basis.
Forward only
Read only
Does support multiple recordsets
Dim strConnectionString, sSQL As String
'SQL Connection String
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\
MyDatabase1.mdb"
strSQL = "SELECT Title FROM YourTable1"
Dim conn As New System.Data.OleDb.OleDbConnection(strConnectionString)
Dim cmd As New System.Data.OleDb.OleDbCommand(strSQL, conn)
Dim dr As System.Data.OleDb.OleDbDataReader
conn.Open()
dr = cmd.ExecuteReader()
Do While dr.Read()
Me.lstTitles.Items.Add(dr.Item("Title"))
Loop
dr.Close()
conn.Close()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickDim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyDatabase1.accdb;Persist Security Info=False;"'initialise the database connectionDim dbCon As OleDb.OleDbConnection = New OleDb.OleDbConnection(strCon)'initialise the commandDim cmd As New OleDb.OleDbCommand'initialise the datareaderDim dr As OleDb.OleDbDataReader'Your SQL select statement goes hereDim strSQL As String = "SELECT * FROM YourTable1"Try
'set the connection to be used in this oledb commandcmd.Connection = dbCon
'set the sql statement for the commandcmd.CommandText = strSQL
'open db connectiondbCon.Open()'execute the readerdr = cmd.ExecuteReader
While dr.ReadMe.TextBox1.Text &= dr.Item("Title") & " "
End While
dr.Close()Catch ex As System.Data.OleDb.OleDbException
MessageBox.Show(ex.Message)Exit Sub
Finally'finally close the database connection to avoid deadlocks and errorscmd.Dispose()dbCon.Close()
End Try
End Sub
In-memory representation of data contained in a database/XML
Operations are performed on the DataSet, not the data source
Can be created programmatically, using a DataAdapter or XML schema and document (or any mixture)
Pipeline between DataSets and data sources
Geared towards functionality rather than speed
Disconnected by design
Supports select, insert, delete, update commands and methods
Must always specify a select command
All other commands can be generated or specified
A DataSet contains one or more DataTables.
Fields are held within the DataTable.
And in DataRows, DataColumns.
DataSet
DataTable
DataRelation
DataRow
DataColumn
New to ADO.Net
Tables within a DataSet can now have relationships, with integrity.
Supports cascading updates and deletes.
Like a SQL view
Single, or multiple tables
Normally used with GUI applications via Data Binding.
Imports System.DataImports System.Data.OleDb
' some code here Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' create a connection string Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb"
Dim myConnection As OleDbConnection = New OleDbConnectionmyConnection.ConnectionString = connString
' create a data adapter Dim da As OleDbDataAdapter = New OleDbDataAdapter("Select * from Customers", myConnection)
' create a new dataset Dim ds As DataSet = New DataSet
' fill dataset da.Fill(ds, "Customers")
' Attach DataSet to DataGridDataGrid1.DataSource = ds.DefaultViewManager
End Sub
End Class
DataSet
Client
DataAdapter
Database
Server
DataUpdate
DeleteCommand
UpdateCommand
InsertCommand
Data
DataTable
Fill
Imports System.Data.OleDbPublic Class Form2 Inherits System.Windows.Forms.FormDim cn As OleDbConnectionDim cmd As OleDbCommandDim dr As OleDbDataReaderDim icount As IntegerDim str As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_System.EventArgs) Handles Button2.ClickTrycn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\emp.mdb;")cn.Open()str = "insert into table1 values(" & CInt(TextBox1.Text) & ",'" & TextBox2.Text & "','" &_TextBox3.Text & "')"'string stores the command and CInt is used to convert number to stringcmd = New OleDbCommand(str, cn)icount = cmd.ExecuteNonQueryMessageBox.Show(icount)'displays number of records insertedCatchEnd Trycn.Close()End SubEnd Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdatePassword.ClickDim strCon As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Downloads\MyDatabase1.accdb;Persist Security Info=False;"Dim oledbCon As OleDbConnection = New OleDbConnection(strCon)Dim strSQL As New System.Text.StringBuilderDim cmd As OleDbCommand = New OleDbCommand
Try
Dim strUserName As String = txtUserName.Text.TrimDim strPassword As String = txtNewPassword.Text.Trim
'set connection for this commandcmd.Connection = oledbCon'open the connectionoledbCon.Open()
'sql syntaxstrSQL.Append("Update tblUsers SET ")strSQL.Append("Pwd='" & strPassword & "'")strSQL.Append("WHERE (UserName='" & strUserName & "')")
cmd.CommandText = strSQL.ToStringcmd.ExecuteNonQuery()
MessageBox.Show("Your password is successfully Updated!", "Update Status", MessageBoxButtons.OK, MessageBoxIcon.Information)Me.Close()
Catch Exp As OleDbExceptionMessageBox.Show(Exp.message, "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch Exp As ExceptionMessageBox.Show(Exp.Message, "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
FinallyTry
oledbCon.Close()cmd.Dispose()
CatchEnd Try
End TryEnd Sub
Question – 1Create a database named Emp in Microsoft Access in the C: drive of your machine. In the Emp database create a table, Table1 with EmpNo, EName and Department as columns, insert some values in the table and close it. Open Visual Studio .NET, on a new form drag three TextBoxes and a Button. The code on the next slide will assume that TextBox1 is for EmpNo, TextBox2 is for EName and TextBox3 is for Department. Our intention is to retrieve data from Table1 in the Emp Database and display the values in these TextBoxes without binding when the Button is clicked.
Question – 1 codeImports System.Data.OleDbPublic Class Form1 Inherits System.Windows.Forms.FormDim cn As OleDbConnectionDim cmd As OleDbCommandDim dr As OleDbDataReaderPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e as _System.EventArgs) Handles MyBase.LoadEnd Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_System.EventArgs) Handles Button1.ClickTrycn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;_Data Source=C:\emp.mdb;")'provider to be used when working with access databasecn.Open()cmd = New OleDbCommand("select * from table1", cn)dr = cmd.ExecuteReaderWhile dr.Read()TextBox1.Text = dr(0)TextBox2.Text = dr(1)TextBox3.Text = dr(2)' loading data into TextBoxes by column indexEnd WhileCatchEnd Trydr.Close()cn.Close()End SubEnd Class