PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A...

23
PLATFORM TECHNOLOGY UNIT-4 Y3/S5 ADO.NET Object Model ADO.NET object model provides an infrastructure that allows user access data from dif- ferent Data Sources. ADO.NET provides a set of classes for working with data. ADO.NET is a set of classes, interfaces, structures and enumerations that manage data access in the .net framework ADO.NET has following attributes: 1. Consists of set of classes that user can use to connect to and manipulate data source 2. Transfer data into xml format between the database and your web application etc. There are two main component of this object model Dataset and Net data provider DATASET The dataset is a disconnected, in-memory representation of data. It can be considered as a local copy of the relevant portions of the database. The DataSet is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this DataSet is finished, changes can be made back to the central database for updating. The data in DataSet can be loaded from any valid data source like Microsoft SQL server database, an Oracle database or from a Microsoft Access database. Dataset Datatable DataTable Odbc provider Sqlserver data provider Oledb.Netprovider Oracle Dataprovider Odbc sources Sqlserver Oledb sources Oracle sources DATA PROVIDERS RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 1 VB .NET: Handling Exceptions – Delegates and Events - Accessing Data – ADO.NET Object Model- .NET Data Providers – Direct Access to Data – Accessing Data with Datasets.

Transcript of PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A...

Page 1: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

ADO.NET Object Model

ADO.NET object model provides an infrastructure that allows user access data from dif-ferent Data Sources.

ADO.NET provides a set of classes for working with data. ADO.NET is a set of classes, interfaces, structures and enumerations that manage data access in the .net framework

ADO.NET has following attributes:

1. Consists of set of classes that user can use to connect to and manipulate data source2. Transfer data into xml format between the database and your web application etc.

There are two main component of this object model

Dataset and Net data provider

DATASET

The dataset is a disconnected, in-memory representation of data.

It can be considered as a local copy of the relevant portions of the database.

The DataSet is persisted in memory and the data in it can be manipulated and updatedindependent of the database.

When the use of this DataSet is finished, changes can be made back to the centraldatabase for updating.

The data in DataSet can be loaded from any valid data source like Microsoft SQL serverdatabase, an Oracle database or from a Microsoft Access database.

DatasetDatatable DataTable

Odbc provider Sqlserver data provider Oledb.Netprovider Oracle DataproviderOdbc sources Sqlserver Oledb sources Oracle sources

DATA PROVIDERS

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 1

VB .NET: Handling Exceptions – Delegates and Events - Accessing Data – ADO.NET Object

Model- .NET Data Providers – Direct Access to Data – Accessing Data with Datasets.

Page 2: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

ADO.NET Data Providers are class libraries that allow a common way to interact with specific data sources or protocols. The library APIs have prefixes that indicate which provider they sup-port

DATA PROVIDER

The Data Provider is responsible for providing and maintaining the connection to thedatabase. A DataProvider is a set of related components that work together to provide data in anefficient and performance driven manner. The .NET Framework currently comes with twoDataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQLServer 7.0 or later and the OleDb DataProvider which allows us to connect to other types ofdatabases like Access and Oracle. Each DataProvider consists of the following componentclasses:

Connection object

Command object

DataReader object

DataAdapter object

Component classes that make up the Data Providers

The Connection Object

The Connection object creates the connection to the database.

Microsoft Visual Studio .NET provides two types of Connection classes:the SqlConnection object, which is designed specifically to connect to Microsoft SQLServer 7.0 or later, and

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 2

Page 3: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

the OleDbConnection object, which can provide connections to a wide range ofdatabase types like Microsoft Access and Oracle.

The Connection object contains all of the information required to open a connection tothe database.

The Command Object

The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand.

Command objects are used to execute commands to a database across a data connection.

The Command objects can be used to execute stored procedures on the database, SQL commands, or return complete tables directly.

Command objects provide three methods that are used to executecommands on the database:

ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE ExecuteScalar: Returns a single value from a database query Executereader: Returns a result set by way of a DataReader object

The DataReader Object

The DataReader object provides a forward-only, read-only, connected stream recordsetfrom a database.

Unlike other components of the Data Provider, DataReader objects cannot bedirectly instantiated.

DataReader is returned as the result of the Command object's ExecuteReader method.

The SqlCommand.ExecuteReader method returns a SqlDataReader object, and theOleDbCommand.ExecuteReader method returns an OleDbDataReader object.

The DataReader can provide rows of data directly toapplication logic when you do notneed to keep the data cached in memory.

Because only one row is in memory at a time, the DataReader provides the lowestoverhead in terms of system performance but requires the exclusive use of anopen Connection object for the lifetime of the DataReader.

The DataAdapter Object

The DataAdapter is the class at the core of ADO .NET's disconnected data access.

It is essentially the middleman facilitating all communication between the database and aDataSet.

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 3

Page 4: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

The DataAdapter is used either to fill a DataTable or DataSet with data from thedatabase with its Fill method.

After the memory-resident data has been manipulated, the DataAdapter can commit thechanges to the database by calling the Update method.

The DataAdapter provides four properties that represent database commands:

SelectCommand

InsertCommand

DeleteCommand

UpdateCommand

When the Update method is called, changes in the DataSet are copied back to thedatabase and the appropriate InsertCommand, DeleteCommand, or UpdateCommand isexecuted.

.NET DATA PROVIDERS

.NET DATA PROVIDERS

1. Microsoft SQL Server .NET Data Provider (System.Data.SqlClient)The Microsoft SQL Server .NET Data Provide allows you to connect to a MicrosoftSQL Server 7.0, 2000, and 2005 databases.

2. ODBC .NET Data Provider (System.Data.ODBC)3. OLE DB .NET Data Provider (System.Data.OleDb)

.NET DATA PROVIDERS OBJECTS

The Connection object which provides a connection to the database

The Command object which is used to execute a command

The DataReader object which provides a forward-only, read only, connected recordset

The DataAdapter object which populates a disconnected DataSet with data and

performs update

DataColumn object – This is the building block of the DataTable. A number of such

objects make up a table. Each DataColumn object has a DataType property that

determines the kind of data that the column is holding. A control can be bound simply

such as a TextBox to a column within a data table

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 4

Page 5: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

Data Table – A DataTable object is the representation of a table, with rows and columns,

in ADO .NET. A DataTable can be considered to a collection of two kinds viz.,

DataColumn objects and DataRows object. You can complex-bind a control to the

information contained in a data table. Controls like DataGrid are used for this purpose

DataView object – A DataView object is a customized view of a single data table that

may be filtered or sorted. A data view is the data snapshot used by complex-bound

controls. You can simple-bind or complex-bind to the data within the DataView. This is

not an updating data source

.DataSet object – A DataSet is a collection of tables, relationships and constraints. You

can simple-bind or complex bind to the data within the dataset.

.DataViewManager Object – A DataViewManager object is a customized view of the

whole DataSet. It is an extended form of a DataView with realations included and with

multiple tables.

For MS SQL server we have corresponding Connection, Command, datareader and data adapter object

They are:

SqlDataReader

SqlDataAdapter

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 5

Page 6: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

SqlConnection

SqlCommand

Connection string

SqlConnection oSQLConn = new SqlConnection(); oSQLConn.ConnectionString = "Data Source=(local);" + "Initial Catalog=myDatabaseName;" + "Integrated Security=SSPI";

For My SQL we have corresponding Connection, Command, datareader and data adapter object

They are:

OdbcDataReader

OdbcDataAdapter

OdbcConnection

OdbcCommand

Connection string

Dim sConnString As String = "Driver={SQL Server};" & "Server=MySQLServerName;" & _ "Database=MyDatabaseName;" & "Uid=MyUsername;" & "Pwd=MyPassword"

For Oracle server we have corresponding Connection, Command, datareader and data adapter object

They are:

OracleDataReader

OracleDataAdapter

OracleConnection

OracleCommand

For MS Access/ Excel we have corresponding Connection, Command, datareader and dataadapter object

They are:

OledbDataReader

OledbDataAdapter

OledbConnection

OledbCommand

Connection string con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=D:\\employee.mdb";

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 6

Page 7: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

Accessing Data with Datasets

ADO.NET DataSets

The DataSet object is central to supporting disconnected, distributed data scenarios with ADO.NET.

The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source.

It can be used with multiple and differing data sources, with XML data, or to manage data local to the application.

The DataSet represents a complete set of data, including related tables, constraints, and relationships among the tables.

The connection to the database has been made. The next step is to pull the records from the table. To do that, a Dataset and a DataAdapter are needed.

The DataAdapter will fill the Dataset with records from the database. Generally DataSet has two types which are namely as follows:

Typed DataSet: Those Dataset which applies the information contained in theXSD to create a typed class, this DataSet is said to be a Typed Dataset. TypedDataSet are basically used to raed data from XML file.

Untyped DataSet: Untyped DataSet does not have any schema. It is exposedsimply as a mere collection.

The following illustration shows the DataSet object model.

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 7

Page 8: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

The methods and objects in a DataSet are consistent with those in the relational database model.

The DataTableCollection An ADO.NET DataSet contains a collection of zero or more tables represented by

DataTable objects. The DataTableCollection contains all the DataTable objects in a DataSet. A DataTable is defined in the System.Data namespace and represents a single table of

memory-resident data. It contains a collection of columns represented by a DataColumnCollection, and

constraints represented by a ConstraintCollection, which together define the schema of the table.

A DataTable also contains a collection of rows represented by the DataRowCollection, which contains the data in the table. Along with its current state, a DataRow retains both its current and original versions to identify changes to the values stored in the row.

The DataView Class

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 8

Page 9: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

A DataView enables you to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications.

Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression.

The DataRelationCollection

A DataSet contains relationships in its DataRelationCollection object.

A relationship, represented by the DataRelation object, associates rows in one DataTable with rows in another DataTable.

A relationship is analogous to a join path that might exist between primary and foreign key columns in a relational database.

A DataRelation identifies matching columns in two tables of a DataSet.

Relationships enable navigation from one table to another in a DataSet. The essential elements of a DataRelation are the name of the relationship, the name of the tables beingrelated, and the related columns in each table.

Relationships can be built with more than one column per table by specifying an array ofDataColumn objects as the key columns. When you add a relationship to the DataRelationCollection, you can optionally add a UniqueKeyConstraint and a ForeignKeyConstraint to enforce integrity constraints when changes are made to relatedcolumn values.

To create a Dataset object, add the following just above the form load event:

DataSet ds1;

Inside of the form load event, create a new object from the Dataset type we've called ds1:

ds1 = new DataSet();

Add the code just after your con.Open line.

For the DataAdapter, add the following outside of the form load event:

System.Data.SqlServerCe.SqlCeDataAdapter da;

We're setting up a DataAdapter variable, here, and calling it da.

Inside of the form load event, we can create a new object from our da variable. Add these two lines just after your ds1 line:

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 9

Page 10: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

String sql = "SELECT * From tbl_employees";

da = new System.Data.SqlClient.SqlDataAdapter( sql, con );

The first line sets up a string variable called sql. SQL stands for Structured Query Language. It's a language used to pull records from a database, and variants of it are used for all database systems.

ACCESSING DATA WITH DATASETS

Codingusing System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Data.SqlClient;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms; namespace UpdatingData{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { SqlConnection conn = new SqlConnection( @"Data Source=yourServerName;user id=UserName;password=Password;" + "Initial Catalog=DatabaseName"); SqlDataAdapter thisAdapter = new SqlDataAdapter( "SELECT EMPNO,ENAME FROM EMP", conn); SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 10

Page 11: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

DataSet ds = new DataSet(); thisAdapter.Fill(ds, "Employee"); Console.WriteLine("name before change: {0}", ds.Tables["Employee"].Rows[5]["ENAME"]); ds.Tables["Employee"].Rows[5]["ENAME"] = "Johnson"; thisAdapter.Update(ds, "Employee"); Console.WriteLine("name after change: {0}", ds.Tables["Employee"].Rows[5]["ENAME"]); } }}

Here,

SqlConnection conn = new SqlConnection( @"Data Source=yourServerName;user id=UserName;password=Password;" + "Initial Catalog=DatabaseName"); The above block of code is SQL – Server specific connection String to the database

SqlDataAdapter thisAdapter = new SqlDataAdapter( "SELECT EMPNO,ENAME FROM EMP", conn);

Here we create a DataAdapter object to Operations such as Update

SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

The SqlCommandBuilder is used to build SQL statements

DataSet ds = new DataSet();

Here, we create a DataSet object to hold data.

thisAdapter.Fill(ds, "Employee");

In the above statement we will the DataSet with the query we have previously defined for theDataAdapter.

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 11

Page 12: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

Console.WriteLine("Name before change: {0}",ds.Tables["Employee"].Rows[5]["ENAME"]); Displaying the data before change

ds.Tables["Employee"].Rows[5]["ENAME"] = "Johnson";

In the above line, we change the data in Employee table, row 5 with the column name ENAME

thisAdapter.Update(ds, "Employee");

Here we make a call to the Update command to make the changes permanent to the databaseTable.

Console.WriteLine("Name after change: {0}",ds.Tables["Employee"].Rows[5]["ENAME"]);

HOW TO ACCESING DATA WITH ADO.NET

HOW TO ACCESING DATA WITH ADO.NET

Client makes request

Create a sqldatasource

Return the data to the client

Update the data

Use the SQLdatasource to open a data base connection, update the database and close the

connection

The connection to the database has been made. The next step is to pull the records from our Em-ployees table. To do that, a Dataset and a DataAdapter are needed.

A Dataset is where all your data is held when it is pulled from the database table. Think of it like a grid that you see on a spreadsheet. The Columns in the grid are the Columns from your data-base table. The Rows represent a single entry in the table.

The Dataset needs to be filled with data. However, because the Dataset and Connection object can't see each other, they need someone in the middle to help them out - the DataAdapter. The DataAdapter will fill the Dataset with records from the database.

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 12

Page 13: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

Access data using ADO .NET and make changes to it.

Program………….

Listing 1. SqlConnection Demo

using System;using System.Data;using System.Data.SqlClient;/// <summary>/// Demonstrates how to work with SqlCommand objects/// </summary>class SqlCommandDemo{SqlConnection conn;public SqlCommandDemo(){// Instantiate the connectionconn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");}// call methods that demo SqlCommand capabilitiesstatic void Main(){SqlCommandDemo scd = new SqlCommandDemo();Console.WriteLine();Console.WriteLine("Categories Before Insert");Console.WriteLine("------------------------");// use ExecuteReader methodscd.ReadData();// use ExecuteNonQuery method for Insertscd.Insertdata();Console.WriteLine();Console.WriteLine("Categories After Insert");Console.WriteLine("------------------------------");scd.ReadData();// use ExecuteNonQuery method for Updatescd.UpdateData();Console.WriteLine();Console.WriteLine("Categories After Update");Console.WriteLine("------------------------------");scd.ReadData();

// use ExecuteNonQuery method for Deletescd.DeleteData();Console.WriteLine();

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 13

Page 14: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

Console.WriteLine("Categories After Delete");Console.WriteLine("------------------------------");scd.ReadData();

// use ExecuteScalar methodint numberOfRecords = scd.GetNumberOfRecords();Console.WriteLine();Console.WriteLine("Number of Records: {0}", numberOfRecords);}

/// <summary>/// use ExecuteReader method/// </summary>

public void ReadData(){SqlDataReader rdr = null;try{// Open the connectionconn.Open();

// 1. Instantiate a new command with a query and connectionSqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);// 2. Call Execute reader to get query results

rdr = cmd.ExecuteReader();// print the CategoryName of each record

while (rdr.Read()){Console.WriteLine(rdr[0]);}}finally{// close the readerif (rdr != null){rdr.Close();}// Close the connectionif (conn != null){conn.Close();}

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 14

Page 15: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

}}

/// <summary>/// use ExecuteNonQuery method for Insert/// </summary>

public void Insertdata(){try{// Open the connectionconn.Open();

// prepare command stringstring insertString = @"insert into Categories (CategoryName, Description)values 'Miscella-neous', 'Whatever doesn''t fit elsewhere')";

// 1. Instantiate a new command with a query and connectionSqlCommand cmd = new SqlCommand(insertString, conn);

// 2. Call ExecuteNonQuery to send commandcmd.ExecuteNonQuery();}finally{// Close the connectionif (conn != null){conn.Close();}}}/// <summary>/// use ExecuteNonQuery method for Update/// </summary>

public void UpdateData(){try{// Open the connectionconn.Open();// prepare command stringstring updateString = @"update Categories set CategoryName = 'Other' where CategoryName = 'Miscellaneous'";

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 15

Page 16: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

// 1. Instantiate a new command with command text onlySqlCommand cmd = new SqlCommand(updateString);

// 2. Set the Connection propertycmd.Connection = conn;

// 3. Call ExecuteNonQuery to send commandcmd.ExecuteNonQuery();}finally{// Close the connectionif (conn != null){conn.Close();}}}

/// <summary>/// use ExecuteNonQuery method for Delete/// </summary>

public void DeleteData(){try{// Open the connectionconn.Open();

// prepare command stringstring deleteString = @"delete from Categories where CategoryName = 'Other'";

// 1. Instantiate a new commandSqlCommand cmd = new SqlCommand();

// 2. Set the CommandText propertycmd.CommandText = deleteString;

// 3. Set the Connection propertycmd.Connection = conn;

// 4. Call ExecuteNonQuery to send commandcmd.ExecuteNonQuery();

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 16

Page 17: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

}finally{// Close the connectionif (conn != null){conn.Close();}}}

/// <summary>/// use ExecuteScalar method/// </summary>/// <returns>number of records</returns>

public int GetNumberOfRecords(){int count = -1;try{// Open the connectionconn.Open();// 1. Instantiate a new commandSqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);

// 2. Call ExecuteScalar to send commandcount = (int)cmd.ExecuteScalar();}finally{// Close the connectionif (conn != null){conn.Close();}}return count;}}

(OR)

ACCESSING DATA USING ODBC CONNECTIVITY

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 17

Page 18: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

FORM DESIGN

SOURCE CODE

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Data.Odbc;

namespace DBCSHARP

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 18

Page 19: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

{ public partial class Form1 : Form { OdbcConnection con; OdbcCommand com; OdbcDataReader rp; public Form1() { InitializeComponent(); }

private void Form1_Load(object sender, EventArgs e) { con = new OdbcConnection(); com = new OdbcCommand(); con.ConnectionString = "Driver={Microsoft ODBC for Oracle};Server=localhost;Uid=system;Pwd=cse;"; con.Open(); com.Connection = con; }

private void button1_Click(object sender, EventArgs e) { if ((String.IsNullOrEmpty(this.t_reg.Text)) || (string.IsNullOrEmpty(this.t_name.Text)) || (string.IsNullOrEmpty(this.t_dept.Text)) || (string.IsNullOrEmpty(this.t_add.Text))) { MessageBox.Show("please fill all the details"); } com.CommandText = "insert into table2 values(" + this.t_reg.Text + ",'" + this.t_name.Text + "','" + this.t_dept.Text + "','" + this.t_add.Text + "')"; com.ExecuteNonQuery(); MessageBox.Show("Record Inserted");

}

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 19

Page 20: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

private void button2_Click(object sender, EventArgs e) { com.CommandText = "update table2 set name='" + t_name.Text + "',dept='" + t_dept.Text + "',address='" + t_add.Text + "' where regno =" + combo.SelectedItem + ""; com.ExecuteNonQuery(); MessageBox.Show("Record Updated"); this.t_reg.Clear(); this.t_name.Clear(); this.t_dept.Clear(); this.t_add.Clear(); }

private void button3_Click(object sender, EventArgs e) { com.CommandText = "delete from table2 where regno=" + this.combo.SelectedItem + ""; com.ExecuteNonQuery(); this.combo.Items.Remove(combo.SelectedItem); this.t_reg.Clear(); this.t_name.Clear(); this.t_dept.Clear(); this.t_add.Clear(); MessageBox.Show("Record Deleted"); }

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { com.CommandText = "select*from table2 where regno=" + combo.SelectedItem + ""; rp = com.ExecuteReader(); if (rp.Read()) { this.t_name.Text = rp.GetString(1); this.t_dept.Text = rp.GetString(2);

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 20

Page 21: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

this.t_add.Text = rp.GetString(3); } rp.Close(); }

private void radioButton2_CheckedChanged(object sender, EventArgs e) { this.t_reg.Hide(); this.combo.Items.Clear(); this.button1.Enabled = false; this.combo.Visible = true; this.button2.Enabled = true; this.button3.Enabled = true; com.CommandText = "select* from table2"; rp = com.ExecuteReader(); while (rp.Read()) { this.combo.Items.Add(rp.GetValue(0)); } rp.Close();

}

private void radioButton1_CheckedChanged(object sender, EventArgs e) { this.t_reg.Show(); this.t_reg.Clear(); this.t_name.Clear(); this.t_dept.Clear(); this.t_add.Clear(); this.combo.Visible = false; this.button1.Enabled = true; this.button2.Enabled = false; this.button3.Enabled = false;

}

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 21

Page 22: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

}}

DATABASE DESIGN

REGNO NAME DEPT ADDRESS

1 AA CSE 12,WDFWF

2 BB ECE 13,SGFRGY

3 CC EEE 14,FGFS

4 DD MECH 16,DRGEY

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 22

Page 23: PLATFORM TECHNOLOGY Y3/S5 YEAR/PLATFORM TECHNOLOGY/Unit 4.pdf · PLATFORM TECHNOLOGY UNIT-4 Y3/S5 A DataView enables you to create different views of the data stored in a DataTable,

PLATFORM TECHNOLOGYUNIT-4

Y3/S5

RAJIV GANDHI COLLEGE OF ENGINEERING & TECHNOLOGY/CSE Page 23