You are on page 1of 48

HỆ QUẢN TRỊ CƠ SỞ DỮ LIỆU

ADO.NET
Nhóm 32:
Nguyễn Thanh Lai.
Nguyễn Lê Phương Thảo.
Đàm Vị Toàn.

INTRODUCTION ADO.NET
o The SqlConnection
o The SqlCommand
o Reading Data with the

SqlDataReader
o Working with Disconnected Data -

The DataSet and SqlDataAdapter
o Adding Parameters to Commands.
o Using Stored Procedures

INTRODUCTION ADO.NET
o ADO.NET is an object-oriented set of
libraries that allows you to interact
with data sources.

o The data source is a database, a text
file, an Excel spreadsheet, or an XML
file.

o For the purposes of this tutorial, we

THE ADO.NET OBJECT MODEL

OleDb Data Data Sources that expose an OleDb OleDb Provider interface. IBM Provider DB2. i. . Oracle Data Oracle For Oracle Databases. and Oracle.e. Access or Excel.DATA PROVIDERS Provider API Data Source Description Name prefix ODBC Data Data Sources with an ODBC Odbc Provider interface. Normally older data bases. Provider SQL Data For interacting with Microsoft SQL Sql Provider Server. SQL Server. Generic access to many databases Borland Data Bdp such as Interbase.

. password. THE SQLCONNECTION OBJECT o A connection object is used by command objects so they will know which database to execute the command on. the database name.I. and other parameters that are required for connecting to the data base. o Identify the database server. user name.

NET DATABASE CONNECTION MODEL .ADO.

Password = @123456”).CREATING A SQLCONNECTION OBJECT o Create new SqlConnection SqlConnection sqlConnection = new SqlConnection( “Data Source=(local). . o The SqlConnection object instantiated above uses a constructor with a single argument of type string. Initial Catalog=UEH. This argument is called a connection string. User ID = sa.

or IP Address.ADO. Integrated Set to SSPI to make connection with user's Security Windows login User ID Name of user configured in SQL Server. . Data Source machine domain name. Password Password matching SQL Server User ID.NET CONNECTION STRING PARAMETERS Parameter Description Name Identifies the server. Could be local machine. Initial Catalog Database name.

USING A SQLCONNECTION o The purpose of creating a SqlConnection object is so you can enable other ADO.NET objects. o Other ADO.NET code to work with a database. such as a SqlCommand and a SqlDataAdapter take a connection object as a parameter. .

THE SEQUENCE OF OPERATIONS OCCURRING OF A SQLCONNECTION: 1. 2. Pass the connection to other ADO. 5. Instantiate the SqlConnection. 4.NET objects. Perform database operations with the other ADO. Open the connection.NET objects. 3. Close the connection. .

SQLCONNECTION DEMO .

II. THE SQLCOMMAND OBJECT .

o The SqlCommand object can be used to support disconnected data management scenarios. modify. and delete commands on rows of data in a database table. such as the number of records in a table. insert.THE SQLCOMMAND OBJECT o A SqlCommand object allows you to specify what type of interaction you want to perform with a database. . o You can do select. or retrieve a single value from a database.

sqlConnection). o SqlCommand has a few overloads (see later…) . o It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object. o The line above is typical for instantiating a SqlCommand object.CREATING A SQLCOMMAND OBJECT o Create new SqlCommand SqlCommand sqlCommand= new SqlCommand(“SELECT Name FROM Accounts".

QUERYING DATA o When using a SQL select command. you retrieve a data set for viewing .

.QUERYING DATA o In the example. passing the command string and connection object to the constructor. we instantiate a SqlCommand object. o Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object.

INSERTING DATA o To insert data into a database. use the ExecuteNonQuery method of the SqlCommand object. .

but it is basically the same.INSERTING DATA o The SqlCommand instantiation is just a little different from what you've seen before. o The ExecuteNonQuery method on the SqlCommand will return number of row affected after excute a Insert Data .

.UPDATING DATA o The ExecuteNonQuery method is also used for updating data.

UPDATING DATA o This time we used a different SqlCommand constructor that takes only the command. . o In step 2. o The ExecuteNonQuery method performs the update command. we assign the SqlConnection object to the Connection property of the SqlCommand object.

.DELETING DATA o You can also delete a record from a database using the ExecuteNonQuery method.

DELETING DATA o This example uses the SqlCommand constructor with no parameters. it explicity sets the CommandText and Connection properties of the SqlCommand object. . o Instead. o The ExecuteNonQuery method call sends the command to the database.

GETTING SINGLE VALUES o Sometimes all you need get from a database is a single value. o The best choice is to let the database perform the work and return just the single value you need. . o Performing an ExecuteReader and calculating the result in your code is not the most efficient way to do this. which could be a count. or other aggregated value from a data set. average. sum.

GETTING SINGLE VALUES .

. we use a cast operator to convert the value to int. This query will only return a single value. o The ExecuteScalar method in step 2 returns this value. o Since the return type of ExecuteScalar is type object.GETTING SINGLE VALUES o The query in the SqlCommand constructor obtains the count of all records from the Accounts table.

III. o It doesn't have overhead associated with traversing the data or writing it back to the data source. o The forward only design of the SqlDataReader is what enables it to be fast. . THE SQLDATAREADER o You can read from SqlDataReader objects in a forward-only sequential manner and will not be able to go back and read it again.

READING DATA WITH THE SQLDATAREADER .

o The SqlCommand object references the connection and the SQL statement necessary for the SqlDataReader to obtain data. like this: SqlDataReader dataReader = sqlCommand. . returns a SqlDataReader instance. o The ExecuteReader method of the SqlCommand object.NET objects.ExecuteReader(). You must call ExecuteReader on a command object.CREATING A SQLDATAREADER OBJECT o Getting an instance of a SqlDataReader is a little different than the way you instantiate other ADO.

you would have to create a new instance of the SqlDataReader and read through the data stream again. you must pull data from a table row-by-row Once a row has been read. o To read this data. . o To read that row again.READING DATA o The SqlDataReader returns data via a sequential stream. the previous row is no longer available.

just like you need to close the SqlConnection.FINISHING UP o Always remember to close your SqlDataReader. .

WORKING WITH DISCONNECTED DATA - THE DATASET AND SQLDATAADAPTER o A DataSet is an in-memory data store that can hold numerous tables.IV. o The SqlDataAdapter opens a connection only when required and closes it as soon as it has performed its task. It is the SqlDataAdapter that manages connections with the data source and gives us disconnected behavior. . o DataSets only hold data and do not interact with a data source.

THE DATASET AND SQLDATAADAPTER .

Write changes from DataSet to data source 3. Close connection o And performs the following actions when updating data source with DataSet changes: 1. Close connection .THE DATASET AND SQLDATAADAPTER o The SqlDataAdapter performs the following tasks when filling a DataSet with data: 1. Open connection 2. Retrieve data into DataSet 3. Open connection 2.

the application becomes more scalable. data source connections are closed and you are free to read and write data with the DataSet as you need. .THE DATASET AND SQLDATAADAPTER o In between the Fill and Update operations. o These are the mechanics of working with disconnected data. o Because the applications holds on to connections only when necessary.

which is used if you were to serialize the data to XML. the DataSet is empty and you need a SqlDataAdapter to load it.CREATING A DATASET OBJECT o Create a new instance without parameters: DataSet dsAccounts = new DataSet(). . o However there is one overload that accepts a string for the name of the DataSet. o Right now.

CREATING A SQLDATAADAPTER o The SqlDataAdapter holds the SQL commands and connection object for reading and writing data. . o You initialize it with a SQL select statement and connection object: SqlDataAdapter daAccounts = new SqlDataAdapter( “SELECT * FROM Accounts". sqlConnection).

.CREATING A SQLDATAADAPTER o The SQL select statement specifies what data will be read into a DataSet. should have already been instantiated. o The connection object. conn. It is the SqlDataAdapter's responsibility to open and close the connection during Fill and Update method calls. but not opened.

These are added to the SqlDataAdapter after it is instantiated. but didn't show the insert.CREATING A SQLDATAADAPTER o As indicated earlier. o There are two ways to add insert. update. and delete statements. and delete commands: via SqlDataAdapter properties or with a SqlCommandBuilder. . o The code showed how to specify the select statment. the SqlDataAdapter contains all of the commands necessary to interact with the data source. update.

.FILLING THE DATASET o You can fill data to the DataSet by using the Fill method of the SqlDataAdapter: daAccounts.Fill(dsAccounts. o The Fill method takes two parameters: a DataSet and a table name. The DataSet must be instantiated before trying to fill it with data. "Accounts"). o The second parameter is the name of the table that will be created in the DataSet.

o To specify exactly which table to use. is assign the DataSet to the DataSource property of the DataGrid.DataSource = dsAccounts. set the DataGrid's DataMember property to the name of the table. Here's an example that assigns the DataSet to a Windows forms DataGrid: dgAccounts. o The first thing we do. . dgAccounts.USING THE DATASET o A DataSet will bind with both ASP.DataMember = "Accounts". in the code above.NET and Windows forms DataGrids.

from the DataSet. daAccounts. is called on the SqlDataAdapter instance that originally filled the dsCustomers DataSet. and Delete properties of the SqlDataAdapter contain the SQL statements used to make database modifications. The second parameter to the Update method specifies which table. o The table contains a list of records that have been modified and the Insert. to update. Update. o The Update method.Update(dsAccounts. above. "Accounts").UPDATING CHANGES o The following code shows how to use the Update method of the SqlDataAdapter to push modifications back to the database. .

o Using parameterized queries is a three step process: 1.V. Assign the SqlParameter object to the SqlCommand object's Parameters property. ADDING PARAMETERS TO SQLCOMMANDS o Makes your application much more secure. assigning values as appropriate. Construct the SqlCommand command string with parameters. 2. Declare a SqlParameter object. 3. .

ADDING PARAMETERS TO SQLCOMMANDS .

. USING STORED PROCEDURES o A stored procedures is a pre-defined. which makes them more efficient to use. reusable routine that is stored in a database. you can take advantage of the reuse and performance benefits of stored procedures. o SQL Server compiles stored procedures.VI. rather than dynamically building queries in your code. o Therefore.

the CommandText in the SqlCommand will be interpreted as the name of a stored procedure .EXECUTING A STORED PROCEDURE o By setting the CommandType to StoredProcedure.

EXECUTING A STORED PROCEDURE .

THE END .