Académique Documents
Professionnel Documents
Culture Documents
AGENDA
1. Fundamentals of ADO.NET 2. Components of ADO.NET 3. More about LINQ 4. Creating connections from Database 5. Queries
FUNDAMENTALS OF ADO.NET
What is ADO.NET ?
ADO is ActiveX Data Object. ADO.NET is the .NET technology for interacting with data sources(such as Microsoft SQL Server, and XML, as per your requirements.) ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file.
ADO.NET(Cont.)
ADO.NET Object Model is based upon the objects of the System.Data namespace. Supports both connected and disconnected architecture: Connected: Application is constantly connected to data source. Provided by DataReader Object. Advantages: Updated data and data concurrency. Disconnected: Connection not constant. Provided by DataSet Object. Advantages: Scalability and performance.
ADO.NET Architecture
Data processing has traditionally been a connection-based, two-tier model. As data processing increasingly uses multi-tier architectures, programmers are switching to a disconnected approach to provide better scalability for their applications.
Two central data access components: .NET Framework Data Providers The DataSet
Architecture of ADO.NET
The architecture of ADO.net, in which connection must be opened to access the data retrieved from database is called as connected architecture.
DataReader : > Forward only > one record at a time > read() :return type bool
The architecture of ADO.net in which data retrieved from database can be accessed even when connection to database was closed is called as disconnected architecture.
DataAdapter : DataAdapter is used to transfer the data between database and dataset. It has commands like select, insert, update and delete. Select command is used to retrieve data from database and insert, update and delete commands are used to send changes to the data in dataset to database. It needs a connection to transfer the data.
USE OF CommandBuilder
CommandBuilder : by default dataadapter contains only the select command and it doesnt contain insert, update and delete commands. > To create insert, update and delete commands for the dataadapter, commandbuilder is used. It is used only to create these commands for the dataadapter and has no other purpose.
DataSet
DataSet : Dataset is used to store the data retrieved from database by dataadapter and make it available for .net application. To fill data in to dataset fill() method of dataadapter is used and has the following syntax. Da.Fill(Ds,TableName);
connected you need to use a read only disconnected you cannot forward only data reader
Data Reader can't persist the data It is Read only, we can't update the data. Data Set can persist the data We can update data
Provider Name
ODBC Data Provider OleDb Data Provider Oracle Data Provider SQL Data Provider Borland Data Provider
Data Sources with an ODBC interface. Normally older data bases. Data Sources that expose an OleDb interface, i.e. Access or Excel. For Oracle Databases. For interacting with Microsoft SQL Server. Generic access to many databases such as Interbase, SQL Server, IBM DB2, and Oracle.
Data Providers
ADO.NET allows us to interact with different types of data sources. HOW? ADO.NET comes in different sets of libraries for each type of a data source. These libraries are called Data Providers. Mainly responsible for providing and maintaining connection to the database.
The DataReader provides a high-performance stream of data from the data source. The DataAdapter provides the bridge between the DataSet object and the data source.
Getting started
Namespace: Using System.Data.SqlClient;
ADO.NET includes many objects you can use to work with data: The SqlConnection Object The SqlCommand Object The SqlDataReader Object The DataSet Object The SqlDataAdapter Object
Using this connection string, create an SqlConnection object, and call its Open() method to establish a connection to your database:
For example, the following connection string points to a local computer that is running SQL Server:
SqlConnection con = new SqlConnection(str);
con.Open();
SqlConnection Object(contd)
Properties and methods: ConnectionString Database ConnectionTimeout Provider DataSource Open Close BeginTransaction
SqlCommand OBJECT
Enables access to the database commands such as SQL statements or stored procedures. After creating a connection, create a SqlCommand object, and pass in the following information: The command that you want to run, and The connection object that you created in the previous step. The following sample code passes in the INSERT statement: string cmd = "INSERT INTO Employee(empId, empName, EmpHireDate) + "VALUES ('MSD12923F', 'Duncan', '2001-01-01');
SqlCommand objCmd = new SqlCommand( cmd, con );
SqlCommand(contd)
Properties & Methods:
CommandText Connection Parameters ExecuteNonQuery() ExecuteReader() ExecuteScalar()
SqlCommand(contd)
Methods:
Item Description
ExecuteReader
ExecuteNonQuery
Executes the query, and does not collect any results. Generally used for queries such as UPDATE and DELETE.
ExecuteScalar
Executes the query, and returns a single value (from the first column of the first row).
METHODS
1. ExecuteNonQuery()
If we're not interested in the result of a query (other than whether it executed successfully or not). Returns an integer value specifying the rows affected by the insert, delete and update. For example, // create the command object
SqlCommand sqlComm = new SqlCommand( "DELETE FROM users WHERE userid=1", sqlConn ); sqlComm.ExecuteNonQuery();
2. ExecuteScalar()
Returns the value of the first column of the first row returned. We need to cast the result to the appropriate data type.
For example,// create the command object SqlCommand sqlComm = new SqlCommand("SELECT COUNT(*) FROM users", sqlConn); int userCount = (int)sqlComm.ExecuteScalar();
3. ExecuteReader()
When we're retrieving multiple rows and columns of data. Returns an instance of a SqlDataReader object using Connection. Provides read-only forward access to rows returned by the SqlCommand object.
ExecuteReader() Procedure
1. Call the read() method: which advances the reader to the first row (and then to the next row on subsequent calls), and returns a boolean value indicating whether there was actually a row to read. Access any columns that we need to. If you want to access them by name probably the most common and readable option - you can use the reader's indexer: Call close() on the DataReader(and the database connection, if need be).
2.
1.
Example: SqlCommand sqlComm = new SqlCommand("SELECT userid, username FROM users ORDER BY username", sqlConn); SqlDataReader r = sqlComm.ExecuteReader(); while ( r.Read() ) { string username = (string)r["username"]; int userID = (int)r["userid"]; ConsoleWriteLine(username + "(" + userID + ")"); } r.Close();
Example: string sSQL = "DELETE FROM Employee WHERE emp_id = @emp_id The parameter name ("@emp_id") in this DELETE statement represents a parameter than you can replace with different values each time you run the command.
Using Parameters(contd)
To use parameters with your command, follow these steps: Create your SqlConnection object. Replace values with placeholders (for example, "@emp_id" or "@fname") so that your command text uses parameters. Create your SqlCommand object, and pass in the connection object that you created in the first step and the command text that contains the parameter placeholders.
For each parameter, add a parameter object to the command object's parameters collection. For each parameter, you must specify a name and data type: objCmd.Parameters.Add("@emp_id", SqlDbType.Char, 9); You must also set a value for each input parameter before you can run the query: objCmd.Parameters["@emp_id"].Value = "MSD12923F"; Run the query as follows: objCmd.ExecuteNonQuery();
System.Data.SqlClient Namespace
.NET Framework Data Provider for SQL Server.
The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space. Using the SqlDataAdapter, you can fill a memory-resident DataSet, which you can use to query and update the database. Main classes: SqlDataAdapter SqlDataReader SqlCommand SqlConnection
When you click on Add New Item, you should see the following dialogue box appear. Select Service-based database (or SQL Database for older versions). Give your database a name. Call it MyWorkers.mdf. We'll create a database of fictitious people who work for us, and give them job descriptions. Click the Add button.
In C# 2010 you're then asked to choose a Database model. Leave it on the default of Dataset and click Next. In earlier versions of C#, you'll see the following
Select Tables, and then Finish. (The Dataset is important, and you'll see how they work later). In C# 2010, you'll see this:
However, your database is empty at the moment. We need to add a table to it. So right click on MyWorkers.mdf. From the menu that appears, click Open. You should see the Database Explorer appear:
Select Add New Table from the menu, and a new table will appear in your main window:
Click File > Save All to save your work. You will be prompted to enter a name for your new table. Call it tblWorkers:
Click OK and you'll be returned to the main screen and the Database Explorer. Expand the Tables section and you should see your new columns appear:
QUERIES
DATA READER:
1.Create connection Close down the project you have open, and click File > New Project to create a new one.
To find the MDF database you created in the previous section, look in the Projects folder of Visual Studio 2010. Double click the name you gave to your project and you should see the MyWorkers.mdf file. Copy that mdf database anywhere \Copy it somewhere like the root of C:\
Click Add New Data Source and you'll see a Wizard appear. On the first screen, make sure Database is selected and then click the Next button get to the Choose your Data Connection step. Click the New Connection button, and you'll see the following:
The Data Source area has a Change button. Click this to see the following:
Click the Browse button and browse to the location where you saved your database. The Add Connection box will then look something like this:
Click the Test Connection button to see if everything is working. Then click OK to get back to the Choose your Data Connection step. Expand the Connection Stringarea, and the dialogue box should look like this:
Code snippet:
1. Creating connection: SqlConnection con=new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\dell\\Document s\\Database1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
2. Insert
command=new SqlCommand("SET IDENTITY_INSERT studentrecord ON insert into studentrecord(student_name,student_rollno) values('" + textBox1.Text + "','" + textBox2.Text + "')SET IDENTITY_INSERT studentrecord OFF ", con);
command.Parameters.Clear(); command.Parameters.AddWithValue("@student_name", textBox1.Text); command.Parameters.AddWithValue("@student_rollno", textBox2.Text); try { con.Open(); int result = command.ExecuteNonQuery(); if (result > 0) MessageBox.Show("record inserted."); else MessageBox.Show("Failed to add record."); } catch (SqlException ex) { MessageBox.Show(ex.Message); } finally { con.Close(); }
3.Update
command = new SqlCommand("Update studentrecord SET student_name = '" + textBox1.Text + "' WHERE student_rollno = '" + textBox2.Text + "'", con);
command.Parameters.Clear(); command.Parameters.AddWithValue("@student_name", textBox1.Text); command.Parameters.AddWithValue("@student_rollno", textBox2.Text); try { con.Open(); int result = command.ExecuteNonQuery(); if (result > 0) MessageBox.Show("record updated."); else MessageBox.Show("Failed to update record."); } catch (SqlException ex) { MessageBox.Show(ex.Message); } finally { con.Close(); }
4.Delete
command.Parameters.Clear(); command.Parameters.AddWithValue("@student_rollno", textBox2.Text); try { con.Open(); int result = command.ExecuteNonQuery(); if (result > 0) MessageBox.Show("record deleted."); else MessageBox.Show("Failed to delete record."); } catch (SqlException ex) { MessageBox.Show(ex.Message); } finally { con.Close(); }
5.Grid view
SqlDataAdapter da1 = new SqlDataAdapter("Select * from studentrecord", con);
Data Adapter
SqlDataAdapter da1 = new SqlDataAdapter("Select * from tblEmployee", con); DataSet ds1 = new DataSet(); da1.Fill(ds1);
LINQ TO SQL
LINQ to SQL is a powerful tool which allows developers to access databases as objects in C#
Getting Started:
We will be creating a Windows Forms Application that allows as to you to query and view records from a particular table using LINQ to SQL classes Creating LINQ to SQL Classes Create a new Windows Forms Application and name it LinqToSqlDemo. (FILE > NEW > PROJECT) In solution explorer right click on lintosqldemo > add new item > linq to sql classes(name it as student.dbml)
CREATE A CONNECTION
Create a connection to the studentrecord database: Choose the Server Explorer from the View menu (Ctrl + W, L). In Express editions of Visual Studio, this tool is called the Database Explorer. Right click on the Data Connections node shown in Figure 3 and choose Add Connection.
Cont..
In the Add Connection dialog select the Browse button and navigate to and select your copy of database1.mdf. Select the OK button.
At this stage database1.mdf should appear in your server or database explorer, as shown in Figure on the next slide.
Select the Browse button in the Add Connection dialog and locate your copy of database1.mdf
The Server Explorer provides a view of the let say Northwind database.
Note: If the Customer class is not available, cancel out of the wizard, build the project, and run the wizard again.
Click Finish to create the data source and add the Customer entity class to the Data Sources window. Drag items from the Data Sources window onto a form.
SQL Designer(contd)
Drag the Customer table from the Server Explorer onto the SQL designer.
When you added the SQL Designer to your project, a new node in the Solution Explorer called DataClasses1.dbml was added to your project. As shown in Figure, it contains two files, called DataClasses1.dbml.layout and DataClasses1.designer.cs. When you dragged the student table onto the designer, an object relational mapping (ORM) was created between the student table in the database and a studentclass generated by the SQL Designer and placed in DataClasses1.designer.cs. This object is called an entity class and it allows you to access the data and fields of the student tables as if they were an object in your project.
A second class, referred to as a DataContext, was also created in DataClasses1.designer.cs. This class can be used to automatically connect to the database and to easily access the data and fields in the Customer table. A file called app.config was added to your project. It contains an automatically generated connection string for your database.
Data Context
From the developers perspective, the architecture for LINQ to SQL is quite simple. Working primarily with a single class called the DataContext, LINQ developers can: 1.Connect to a database 2.Access data 3.Submit changes back to the server
DataContext
After you add a LINQ to SQL file to your project, the empty design surface represents a DataContext ready to be configured. Drag database items from Server Explorer/Database Explorer onto the O/R Designer to create data classes and DataContext methods.
The data connection of a DataContext is created based on the first item added to the designer form Server Explorer/Database Explorer.
DataContext Class
The DataContext is the main conduit by which you retrieve objects from the database and resubmit changes. You use it in the same way that you would use an ADO.NET Connection. The purpose of the DataContext is to translate your requests for objects into SQL queries made against the database and then assemble objects out of the results. The DataContext enables language-integrated query by implementing the same operator pattern as the standard query operators such as Where and Select.
Code snippet
INSERT
UPDATE
var st = (from s in dc.GetTable<studentrecord>() where s.student_rollno == Convert.ToInt16(textBox2.Text) select s).SingleOrDefault(); if (st == null) { System.Data.Linq.Table<studentrecord> stud = dc.GetTable<studentrecord>(); studentrecord objStud = new studentrecord(); objStud.student_rollno = Convert.ToInt16(textBox2.Text); objStud.student_name= textBox1.Text; stud.InsertOnSubmit(objStud); dc.SubmitChanges(); } else { st.student_rollno = Convert.ToInt16(textBox2.Text); st.student_name= textBox1.Text; dc.SubmitChanges(); }
DELETE
var st = (from s in dc.GetTable<studentrecord>() where s.student_rollno == Convert.ToInt16(textBox2.Text) select s).SingleOrDefault(); dc.studentrecords.DeleteOnSubmit(st); dc.SubmitChanges();
GRID VIEW
Table<studentrecord> stud = dc.GetTable<studentrecord>(); dataGridView1.DataSource = dc.GetTable<studentrecord>();