25
ADO. NET ADO. NET

ADO. NET. What is “ADO.Net”? ADO.Net is a new object model for dealing with databases in.Net. Although some of the concepts are similar to the classical

  • View
    220

  • Download
    0

Embed Size (px)

Citation preview

ADO. NETADO. NET

What is “ADO.Net”?What is “ADO.Net”?

ADO.Net is a new object model for dealing ADO.Net is a new object model for dealing with databases in .Net. Although some of twith databases in .Net. Although some of the concepts are similar to the classical ADhe concepts are similar to the classical ADO, there are some new concepts such as tO, there are some new concepts such as the Dataset. he Dataset.

Introduction to ADO.NETIntroduction to ADO.NET

MS-AccessMS-Access MS-SQLMS-SQL DescriptionDescription

NameSpaceNameSpace System.Data.OleDbSystem.Data.OleDbSystem.Data.System.Data.SqlClientSqlClient

ConnectioConnectionn

OleDbConnectionOleDbConnection SqlConnectionSqlConnection opening a connection to opening a connection to the database the database

CommandCommand OleDbCommandOleDbCommand SqlCommandSqlCommand invoking SQL commands invoking SQL commands or stored procedures or stored procedures

RecordSetRecordSet OleDbDataReaderOleDbDataReader SqlDataReaderSqlDataReader connectedconnected forward-only forward-only access to database access to database

DataSetDataSet OleDbDataAdapterOleDbDataAdapter SqlDataAdapterSqlDataAdapter populating a populating a DatasetDataset..

Stored Stored ProcedureProcedure OleDbParameterOleDbParameter SqlParameterSqlParameter specifying parameter to specifying parameter to

a stored procedure a stored procedure

ransactionransaction OleDbTransactionOleDbTransaction SqlTransactionSqlTransaction programming database programming database transactions transactions

Process of using DB (1)Process of using DB (1)

1.1. Import NamespaceImport Namespace2.2. Make ConnectionMake Connection3.3. Open ConnectionOpen Connection4.4. Send QuerySend Query5.5. Execute QueryExecute Query6.6. Store resultStore result7.7. Populate data in UIPopulate data in UI8.8. Close connectionClose connection

Process of using DB (2)Process of using DB (2)SqlConnection conn = new SqlConnection(connstr);SqlConnection conn = new SqlConnection(connstr);//using(SqlConnection conn = new SqlConnection(connstr))//using(SqlConnection conn = new SqlConnection(connstr))

conn.Open();conn.Open();SqlCommand cmd = new SqlCommand(SQLstr,conn);SqlCommand cmd = new SqlCommand(SQLstr,conn);SqlDataReader reader = cmd.ExecuteReader();SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())while (reader.Read()){{ listBox1.Items.Add(reader[1].ToString()); listBox1.Items.Add(reader[1].ToString()); }}conn.Close();conn.Close();

Connection(1) Connection String1. MS-SQL

string connstr = "server=SERVERNAME;uid=USERID;pwd=PASSWORDr;database=DBNAME;";

string connstr = "server=rainnysea;uid=testuser;pwd=testuser;database=Teststd;";

2. MS-Acess string connstr = "Provider=ProviderName&Version;Data Source=F

ileNameOnServer"; string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source

=D:\\cs440\\Test\\data\\xyz.mdb;";

Connection(2)database connections are an important resource and you should explicitly close the connection .

conn = SqlConnection(ConnString);try{

// open the connection to the database conn.Open();

// do something with the database} catch (Exception e) {

// report error} finally {

conn.Close( );}

Execute Method on the Command

ExecuteNonQuery( ) ExecuteNonQuery( ) used when no records are expected in the outused when no records are expected in the output e.g., insert or update sql commands.put e.g., insert or update sql commands.

ExecuteReader( )ExecuteReader( ) returns a connected DataReader (actually Datareturns a connected DataReader (actually DataReader interface) Reader interface)

ExceuteScalar( ) ExceuteScalar( ) returns a single row, useful when returns a single row, useful when verifying login for a particular user. verifying login for a particular user.

ExecuteXmlReader( ) ExecuteXmlReader( ) returns an XML reader. returns an XML reader.

Command(1) – Command(1) – ExecuteScalar()ExecuteScalar()

ExecuteScalar()ExecuteScalar()SqlCommand cmd =SqlCommand cmd = new SqlCommand(qry, this.con );new SqlCommand(qry, this.con );Object obj = cmd.ExecuteScalar();Object obj = cmd.ExecuteScalar(); // returns one row// returns one row

Command(2) – Command(2) – ExecuteReader()ExecuteReader()

ExecuteReader()ExecuteReader()SqlCommand cmd = SqlCommand cmd = new SqlCommand(sql,conn);new SqlCommand(sql,conn);SqlDataReader reader = cmd.ExecuteReader();SqlDataReader reader = cmd.ExecuteReader();

Command(3) – Command(3) – ExecuteNonQuery()ExecuteNonQuery()

ExecuteNonQuery()ExecuteNonQuery()SqlCommand cmd = SqlCommand cmd = new SqlCommand(sql,conn);new SqlCommand(sql,conn);int cntrows = cmd.ExecuteNonQuery();int cntrows = cmd.ExecuteNonQuery();

Data Stored Object(1)

DataReaderDataReader It present a forward-only stream of It present a forward-only stream of data to the application.data to the application.

DataSetDataSet It is an in-memory representation of a colleIt is an in-memory representation of a collection of related data tables. It can be genection of related data tables. It can be generated using the help of a rated using the help of a DataAdapterDataAdapter or fil or filled dynamically by the application led dynamically by the application

DataAdapterDataAdapter A class that is used to fill A class that is used to fill DataSet DataSet object frobject from a data source. om a data source.

Data Stored Object(2)DataReader

Data Source

Data Reader

Application

DataSet

Data Source

Data Set

Application 1

Application 2

Data

Adapter

What is “Data Set”?

A Dataset is a disconnected object that can potentially contain all or part of the database including tables, constraints and their relationships. Thus for using databases in web applications, Dataset can provide a much higher performance for mostly read-only type of data.

The DataSet class can further use DataTable, DataRow, DataColumn, DataRelation and Constraint classes to define its offline data.

What is ths “Data Adapter”?What is ths “Data Adapter”?

DataAdapter class acts as the communicatDataAdapter class acts as the communication point between the DataSet And tha dation point between the DataSet And tha database.abase.

This object is created much the same way This object is created much the same way as the Command object.as the Command object.

Fill() method fills DataSet with data obtaineFill() method fills DataSet with data obtained from SQL query.d from SQL query.

DataSet(1)DataSet(1)

DataSet DS = new DataSet();DataSet DS = new DataSet();SqlDataAdapter Adapter = SqlDataAdapter Adapter = new SqlDataAdapter(qry, conn);new SqlDataAdapter(qry, conn);Adapter.Fill(DS, tblName);Adapter.Fill(DS, tblName);

DataGrid Control(1)DataGrid Control(1)

displays data in a series of rows and coludisplays data in a series of rows and columns. mns.

displaying either a single table or the hieradisplaying either a single table or the hierarchical rchical relationshipsrelationships between a set of table between a set of tables. s.

update the data in the bound DataSet, the update the data in the bound DataSet, the DataGrid control reflects the changes. DataGrid control reflects the changes.

DataGrid Control(2)DataGrid Control(2)

dataGrid.DataSource = dataGrid.DataSource = dataset.DefaultViewManager;dataset.DefaultViewManager;

dataGrid.DataSource = dataGrid.DataSource =

dataset.Tables[“tablename"].DefaultView ;dataset.Tables[“tablename"].DefaultView ;

DataGrid Control(2)DataGrid Control(2)

dataset.Relations.Adddataset.Relations.Add("CategoryProducts",("CategoryProducts",ds.Tables["category"].Columns["catID"],ds.Tables["category"].Columns["catID"],ds.Tables["product"].Columns["catID"]);ds.Tables["product"].Columns["catID"]);//(relationship name,//(relationship name,Parent column name,Parent column name,Child column name)Child column name)

Parameterized query(1)Parameterized query(1)

1.1. Construct the SqlCommand command striConstruct the SqlCommand command string with parameters. ng with parameters.

2.2. Declare a SqlParameter object, assigning Declare a SqlParameter object, assigning values as appropriate. values as appropriate.

3.3. Assign the SqlParameter object to the SqlAssign the SqlParameter object to the SqlCommand object's Parameters property.Command object's Parameters property.

Parameterized query(2)Parameterized query(2)

str = "update tblCategory str = "update tblCategory set catdesc = @newname set catdesc = @newname where catdesc = @oldname";where catdesc = @oldname";SqlCommand cmd = SqlCommand cmd = new SqlCommand(str, Conn());new SqlCommand(str, Conn());cmd.Parameters.Add(new SqlParameter("@ncmd.Parameters.Add(new SqlParameter("@n

ewname",newname));ewname",newname));

Stored Procedure(1)Stored Procedure(1)

1.1. A pre-defined, reusable routine that iA pre-defined, reusable routine that is stored in a database. s stored in a database.

2.2. Accept input parameters and return Accept input parameters and return multiple values.multiple values.

3.3. Reduced client/server traffic.Reduced client/server traffic.

Stored Procedure(2)Stored Procedure(2)

CREATE PROCEDURE CREATE PROCEDURE procedure_nameprocedure_name(@(@parameter_nameparameter_name as as datatypedatatype) AS) AS [ Insert into tblcategory(catdesc)[ Insert into tblcategory(catdesc) values(@catDesc)]values(@catDesc)] // SQL Query// SQL QueryGOGO

Stored Procedure(3)Stored Procedure(3)

1.1. create a command object create a command object identifying the stored procedure.identifying the stored procedure.

2.2. set the command object so it set the command object so it knows to execute a stored knows to execute a stored procedure.procedure.

3.3. add parameter to command, add parameter to command, which will be passed to the stored which will be passed to the stored procedure.procedure.

Stored Procedure(4)Stored Procedure(4)

SqlCommand cmd = SqlCommand cmd = new SqlCommand("cateIns", Conn() );new SqlCommand("cateIns", Conn() );cmd.CommandType = cmd.CommandType = CommandType.StoredProcedure;CommandType.StoredProcedure;cmd.Parameters.Addcmd.Parameters.Add (new sqlParameter("@catDesc",(new sqlParameter("@catDesc", SqlDbType.VarChar,50,"catDesc"));SqlDbType.VarChar,50,"catDesc"));cmd.Parameters[0].Value = newname;cmd.Parameters[0].Value = newname;