Unit 5
Unit 5
Import system.data.sqlclient
Public sub main()
Dim connectionString As String
Dim cnn As SqlConnection
connectionString = "Data Source=ServerName;Initial
Catalog=DatabaseName; User ID=UserName;Password=Password"
cnn = New SqlConnection(connectionString)
Try
cnn.Open()
MsgBox.show("Connection Open!")
cnn.Close()
Catch ex As Exception
MsgBox.show("Cannot open connection!")
End Try
End Sub
(2) OleDbConnection
An instance of the OleDbConnection class in .NET Framework is
supported the OLEDB Data Provider.
Imports System.Data.OleDb
Public sub main()
Dim connectionString As String
Dim cnn As OleDbConnection
connetionString="Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=sample.accdb;"
cnn = New OleDbConnection(connectionString)
Try
cnn.Open()
MsgBox.show("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox.show("Cannot open connection ! ")
End Try
End Sub
(3) OdbcConnection
An instance of the OdbcConnection class in .NET
Framework is supported the ODBC Data Provider.
Imports System.Data.Odbc
Public sub main()
Dim connectionString As String
Dim cnn As OdbcConnection
connectionString="Driver={Microsoft Access
Driver(*.mdb)};DBQ=sample.mdb;"
cnn = New OdbcConnection(connectionString)
Try
cnn.Open()
MsgBox.show("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox.show("Cannot open connection ! ")
End Try
End Sub
COMMAND
A command is a SQL statement or a stored procedure used to retrieve,
insert, delete or modify data in a data source.
Dim sqlConnection1 As New SqlConnection("Your Connection
String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader
cmd.CommandText = "SELECT * FROM Customers"
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1
sqlConnection1.Open()
reader = cmd.ExecuteReader()
sqlConnection1.Close()
The different execute commands are describe below:
(1) ExecuteNonQuery
ExecuteNonQuery() is used for executing statements that do not return
result set. ExecuteNonQuery() performs Data Definition tasks as well
as Data Manipulation tasks.
(2) ExecuteReader
ExecuteReader() in SqlCommand Object send the SQL statements to
Connection Object and populate a SqlDataReader Object based on the
SQL statement. It is mainly use to get number of rows from the
database table.
(3) ExecuteScalar
ExecuteScalar() in SqlCommand Object is used for get a single value
from Database after its execution. If the Result Set contains more than
one columns or rows , it takes only the first column of first row, all
other values will ignore.
DATAREADER
Data reader is used to retrieve data from a data source in a read-only and forward-
only mode.
The two types of DataReaders are:
(1) SqlDataReader
SqlDataReader Object provides a connection oriented data access to the SQL
Server data Sources. ExecuteReader() in the SqlCommand Object send the SQL
statements to SqlConnection Object and populate a SqlDataReader Object based
on the SQL statement.
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
SqlDataReader.Read()
(2) OleDbDataReader
OleDbDataReader Object provides a connection oriented data access to the
OLEDB Data Sources. ExecuteReader() in the OleDbCommand Object send the
SQL statements to OleDbConnection Object and populate an OleDbDataReader
Object based on the SQL statement.
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
OleDbDataReader.Read()
Sample Code for SQL Data Reader
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim str As String = "Data Source=.;uid=sa; pwd=123;database=master"
Dim con As New SqlConnection(str)
Try
con.Open()
Dim sql As String = "SELECT * FROM emp;"
Dim cmd As New SqlCommand(sql, con)
Dim myreader As SqlDataReader = cmd.ExecuteReader()
Console.WriteLine("Firstname & lastname ")
Console.WriteLine("=============================")
While myreader.Read()
Console.Write(myreader("Firstname").ToString() & ", ")
Console.Write(myreader("Lastname").ToString() & ", ")
Console.WriteLine("")
End While
Catch ex As SqlException
Console.WriteLine("Error: " & ex.ToString())
End Try
End Sub
End Module
Sample Code for OLEDB Data Reader
Dim myConnection As OleDbConnection = New
OleDbConnection(connString)
' Open connection
myConnection.Open()
Dim cmd As OleDbCommand = New OleDbCommand(cmdString,
myConnection)
cmd.CommandType = CommandType.Text
Dim TheDataReader As OleDbDataReader = cmd.ExecuteReader()
While TheDataReader.Read()
Console.Write(TheDataReader("ContactID").ToString())
Console.Write(" ")
Console.Write(TheDataReader("FirstName").ToString())
Console.Write(" ")
Console.Write(TheDataReader("LastName").ToString())
Console.WriteLine()
End While
Catch ae As OleDbException
MsgBox.show(ae.Message())
End Try
DATAADAPTER
It retrieves data from a database into a dataset and updates the database.
When changes are made to the dataset, the changes in the database are
actually done by the data adapter. The different DataAdapters are:
(1) SqlDataAdapter
SqlDataAdapter provides the communication between the Dataset and
the SQL database. We can use SqlDataAdapter Object in combination
with Dataset Object. It resides in the System.Data.SqlClient namespace.
Dim adapter As New SqlDataAdapter
(2) OleDbDataAdapter
OleDbDataAdapter provides the communication between the Dataset and
the OleDb Data Sources. We can use OleDbDataAdapter Object in
combination with Dataset Object. It resides in the System.Data.OleDb
namespace.
Dim oledbAdapter As OleDbDataAdapter
Sample Code for SQL Data Adapter
Private Sub SqlDataAdapter_Click(ByVal sender As Object, ByVal e As
System.EventArgs)
String ConnectionString = "Integrated Security = SSPI;" +
"Initial catalog = Northwind;" + " Data Source =MAIN-SERVER; "
Dim SQL As String = "SELECT CustomerID, CompanyName FROM
Customers"
Dim conn As SqlConnection = New SqlConnection(ConnectionString)
' open the connection
conn.Open()
'Create a SqlDataAdapter object
Dim adapter As SqlDataAdapter = New SqlDataAdapter(SQL, conn)
' Call DataAdapter's Fill method to fill data from the
' Data Adapter to the DataSet
Dim ds As DataSet = New DataSet("Customers")
adapter.Fill(ds)
' Bind data set to a DataGrid control
dataGrid1.DataSource = ds.DefaultViewManager
End Sub
Sample Code for OLEDB Data Adapter
Private Sub OleDbDataAdapter_Click(ByVal sender As Object, ByVal Args As
System.Event)
'Create a connection object
Dim ConnectionString As String = "provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source= C:/northwind.mdb"
Dim SQL As String = "SELECT * FROM Orders"
Dim conn As OleDbConnection = New OleDbConnection(ConnectionString)
' open the connection
conn.Open()
' Create an OleDbDataAdapter object
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand(SQL, conn)
' Create Data Set object
Dim ds As DataSet = New DataSet("orders")
' Call DataAdapter's Fill method to fill data from the DataAdapter to the
DataSet
adapter.Fill(ds)
dataGrid1.DataSource = ds.DefaultViewManager
End Sub
DATASET
DataSet is an in-memory representation of data. It
is a disconnected, cached set of records that are
retrieved from a database.
When a connection is established with the
database, the data adapter creates a dataset and
stores data in it.
After the data is retrieved and stored in a dataset,
the connection with the database is closed. This is
called the 'disconnected architecture'.
The dataset works as a virtual database containing
tables, rows, and columns.
Components of DataSet
1. DataTable
2. DataTableCollection
3. DataRelation
4. DataRelationCollection
5. ExtendedProperties
6. DataRow
7. DataRowCollection
8. DataView
9. Primary Key
10. Data Column
11. DataColumnCollection
1. DataTable
The DataTable type stores data in memory. It is often used alongside
SQL databases. DataTable has columns and rows properties. DataTable
is an in-memory representation of structured data.
Class Example
Private Sub ShowRows(ByVal table As DataTable)
Console.WriteLine(table.Rows.Count)
For Each row As DataRow In table.Rows
Console.WriteLine(row(1))
Next
End Sub
Private Sub AddRow(ByVal table As DataTable)
Dim rowCollection As DataRowCollection = table.Rows
Dim newRow As DataRow = table.NewRow()
table.Rows.Add(newRow)
End Sub
End Class
8. DataView
It represents a fixed customized view of a DataTable for sorting, filtering, searching,
editing and navigation. The DataView provides different views of the data stored in a
DataTable. The DataView class is typically used for sorting, filtering, searching, editing,
and navigating the data from a DataSet. A DataView is bindable, meaning it can be bound
to controls in the same way that the DataSet can be bound to controls.
Once the design of the form is created, select the View option from
the menu bar. Click on the Properties window.
Select the first text box and the properties for it appear in the
window.
Expand the DataBindings property
Select the Text property for enabling the drop down list.
Click the Add Project Data Source from the drop
down list
Make a connection with the CurrentInfo database and
select the Student table
Select the Other Data Sources, Project Data Sources,
CurrentInfoDataSet, Student table.
Select the Name column and bind it with the textbox.
Bind all the other text boxes with the database values.
Press F5 and execute the Windows Form.
The following output is displayed to the user.
DATA BINDING WITH DATAGRID
CONTROL
Design Time:
Create a Windows Form Application in Visual
Studio .NET. Drag the Datagridview control to the form.
The following customized format is created for user.