Chapter Six Database Programming Ado.net Introducing ADO.Net Most of today's applications need to interact with database systems to persist, edit or view data. In .Net, data access services are provided through ADO.Net components. ADO.Net is an object oriented framework that allows you to interact with database systems. We usually interact with database systems through SQL queries or stored procedures. The best thing about ADO.Net is that it is extremely flexible and efficient. ADO.Net also introduces the concept of a disconnected data architecture. The application stays connected to the DB system even when it is not using DB services. This commonly wastes valuable and expensive database resources, as most of the time applications only query and view the persistent data. ADO.Net solves this problem by managing a local buffer of persistent data called a data set. Your application automatically connects to the database server when it needs to run a query and then disconnects immediately after getting the result back and storing it in the dataset. This design of ADO.Net is called a disconnected data architecture and is very much similar to the connectionless services of HTTP on the internet. It should be noted that ADO.Net also provides connection oriented traditional data access services. Different components of ADO.Net Before going into the details of implementing data access applications using ADO.Net, it is important to understand its different supporting components or classes. All generic classes for data access are contained in the System. Data namespace. Class Description Dataset: the Dataset is a local buffer of tables or a collection of disconnected record sets. Data Table: A Data Table is used to contain data in tabular form using rows and columns. Data Row: Represents a single record or row in a Data Table. Data Column: - Represents a column or field of a Data Table. Data Relation: - Represents the relationship between different tables in a data set.. Constraint : - Represents the constraints or limitations that apply to a particular field or column. ADO.Net also contains some database specific classes. This means that different database system providers may provide classes (or drivers) optimized for their particular database system. Microsoft itself has provided the specialized and optimized classes for their SQL server database system. The name of these classes start with 'Sql' and are contained in the System.Data.SqlClient namespace. 1|Page Similarly, Oracle has also provides its classes (drivers) optimized for the Oracle DB System. Microsoft has also provided the general classes which can connect your application to any OLE supported database server. The name of these classes start with 'OleDb' and these are contained in the System.Data.OleDb namespace. In fact, you can use OleDb classes to connect to SQL server or Oracle database; using the database specific classes. Class Description SqlConnection, OleDbConnection ->represents a connection to the database system. SqlCommand, OleDbCommand ->Represents SQL query. SqlDataAdapter, OleDbDataAdapter ->A class that connects to the database system, fetches the record and fills the dataset. SqlDataReader, OleDbDataReader ->A stream that reads data from the database in a connected design. SqlParameter, OleDbParameter-> represents a parameter to a stored procedure. THE ARCHITECTURE OF ADO.NET Ado.net architecture Performing common data access tasks with ADO.Net Now we will build an application to demonstrate how common data access tasks are performed using ADO.Net. We will use the MS SQL server and MS Access database systems to perform the data access tasks. SQL Server is used because probably most of the time you will be using MS SQL server when developing .Net applications. For SQL server, we will be using classes from the System.Data.SqlClient namespace. Access is used to demonstrate the OleDb databases. For Access we will be using classes from the System.Data.OleDb namespace. Accessing Data using ADO.Net Data access using ADO.Net involves the following steps: I. .Defining the connection string for the database server. 2|Page II. Defining the connection (SqlConnection or OleDbConnection) to the database using the connection string. III. Defining the command (SqlCommand or OleDbCommand) or command string that contains the query IV Defining the data adapter (SqlDataAdapter or OleDbDataAdapter) using the command string and the connection object. V. Creating a new Dataset object VI. If the command is SELECT, filling the dataset object with the result of the query through the data adapter. VII. Reading the records from the Data Tables in the datasets using the Data Row and Data Column objects VIII .If the command is UPDATE, INSERT or DELETE, then updating the dataset through the data adapter X. Accepting to save the changes in the dataset to the database Since we are demonstrating an application that uses both SQL Server and Access databases we need to include the following namespaces in our application: using System.Data; using System.Data.OleDb; // for Access database using System.Data.SqlClient; // for SQL Server Defining the connection string The connection string defines which database server you are using, where it resides, your user name , password and the database name. For SQL Server, we have written the following connection string: // for Sql Server string connectionString = "server= SQLEXPRESS; database=student; un=s; pwd=;"; First of all we have defined the instance name of the server, which is SQLEXPRESS on my system. Next we defined the name of the database, user name (un) and password (pwd). Since my SQL server doesn't have a password for the System Administrator (sa) user, I have left it blank in the connection string. // for MS Access string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;data source = c:\min \stud.mdb"; First we have defined the provider of the access database. Then we have defined the data source which is the address of the target database. Defining a Connection a connection is defined using the connection string. This object is used by the data adapter to connect to and disconnect from the database For SQL Server the connection is created like this: // for Sql Server SqlConnection conn = new SqlConnection (connectionString); 3|Page And for Access the connection is created like this: // for MS Access OleDbConnection conn = new OleDbConnection(connectionString); Defining the command or command string The command contains the query to be passed to the database. Here we are using a command string. We will see the command object (SqlCommand or OleDbCommand) later in the lesson. The command string we have used in our application is: string commandString = "SELECT * from student";//stdent is table name Defining the Data Adapter For SQL Server, the data adapter is created like this: // for Sql Server SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, conn); And for Access, the data adapter is created like this: // for MS Access OleDbDataAdapter dataAdapter = new OleDbDataAdapter(commandString, conn); Creating and filling the DataSet Finally we need to create an instance of the DataSet. As we mentioned earlier, a DataSet is a local & offline container of data. The DataSet object is created simply: DataSet ds = new DataSet(); Now we need to fill the DataSet with the result of the query. We will use the dataAdapter object for this purpose and call its Fill() method. dataAdapter.Fill(ds, "stud"); Here we have called the Fill() method of dataAdapter object. We have supplied it the dataset to fill and the name of the table (DataTable) in which the result of query is filled. This is all we need to connect and fetch data from the database. Now the result of the query is stored in the dataset object in the stud table, which is an instance of the DataTable. We can get a reference to this table by using the indexer property of the dataset object's Tables collection. DataTable dataTable = ds.Tables["stud"]; The indexer we have used takes the name of the table in the dataset and returns the corresponding DataTable object. Now we can use the tables Rows and Columns collections to access the data in the table. 4|Page Example1: Program to Insert data into a table using C#.net public partial class main : Form { OleDbConnection con = new OleDbConnection(); public main() { InitializeComponent(); con.ConnectionString=(@"provider=Microsoft.Ace.OLEDB.12.0;data source = C:\Users\min\Documents\mmm.accdb"); } private void button1_Click(object sender, EventArgs e){ try{ con.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = con; cmd.CommandText = "insert into student(fname,mname,lname) values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')"; cmd.ExecuteNonQuery(); MessageBox.Show("successfull"); con.Close();} catch (Exception ex){ MessageBox.Show("error" + ex);}}} Example1: Program to Insert data into a table using vb.net Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim s As String = "Data Source=. \SQLEXPRESS;Initial Catalog=Sample;Integrated Security=True" Dim con As SqlClient. SqlConnection = New SqlClient. SqlConnection(s) con.Open() Dim i As String = "insert into student values(" + "'" + Me.TextBox1.Text + "'" + "," + "'" + Me.TextBox2.Text + "'" + "," + "'" + Me.TextBox3.Text + "'" + ");" Dim cmd As SqlClient. SqlCommand = New SqlClient. SqlCommand(i, con) cmd.ExecuteNonQuery() con.Close() MsgBox("Data Inserted", vbInformation, "Save") 5|Page Example2: Program to update data from a table using C# .net public partial class main : Form{ OleDbConnection con = new OleDbConnection(); public main() { InitializeComponent(); con.ConnectionString=(@"provider=Microsoft.Ace.OLEDB.12.0;data source = C:\Users\min\Documents\mmm.accdb"); } private void button1_Click(object sender, EventArgs e) { try { conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; string query ="update student set sal='" +textBox2.Text + "'where ID=" + textBox5.Text + ""; cmd.CommandText = query; cmd.ExecuteNonQuery(); MessageBox.Show("Data edited"); conn.Close(); } catch (Exception ex){ MessageBox.Show("Error" + ex);}} Example2: Program to update data from a table using vb.net Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click Dim s As String = "Data Source=. \SQLEXPRESS;Initial Catalog=Sample;Integrated Security=True" Dim con As SqlClient. SqlConnection = New SqlClient. SqlConnection(s) con.Open() Dim i As String = "update student set Sno=" + "'" + Me.TextBox4.Text + "'" + " where sno=" + "'" + Me.TextBox1.Text + "'" + ";" Dim cmd As SqlClient. SqlCommand = New SqlClient. SqlCommand(i, con) cmd.ExecuteNonQuery() con.Close() MsgBox("Data Updated", vbInformation, "Update") End Sub 6|Page Example 3: Program to Delete data from a table using C#.net public partial class main : Form { OleDbConnection con = new OleDbConnection(); public main(){ InitializeComponent(); con.ConnectionString=(@"provider=Microsoft.Ace.OLEDB.12.0;data source = C:\Users\min\Documents\mmm.accdb"); } private void button1_Click(object sender, EventArgs e) { Try{ conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; string query = "delete from student where ID=" + textBox5.Text + ""; cmd.CommandText = query; cmd.ExecuteNonQuery(); MessageBox.Show("Data Deleted"); conn.Close(); } catch (Exception ex) { MessageBox.Show("Error" + ex);}} Example 3: Program to Delete data from a table using VB.net Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click Dim s As String = "Data Source=. \SQLEXPRESS;Initial Catalog=Sample;Integrated Security=True" Dim con As SqlClient. SqlConnection = New SqlClient. SqlConnection(s) con.Open() 'Dim x As Integer = CInt(Me.TextBox1.Text) Dim i As String = "delete from student where sno=" + "'" + Me.TextBox1.Text + "'" + ";" Dim cmd As SqlClient. SqlCommand = New SqlClient. SqlCommand(i, con) cmd.ExecuteNonQuery() con.Close() MsgBox("Data deleted", vbInformation, "Delete") End Sub 7|Page Example 4: Program to search data from a table using C#.net public partial class main : Form { OleDbConnection con = new OleDbConnection(); public main(){ InitializeComponent(); con.ConnectionString=(@"provider=Microsoft.Ace.OLEDB.12.0;data source = C:\Users\min\Documents\mmm.accdb"); } try { conn.Open(); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = conn; string query = "Select * from student where ID = "+textBox1.Text+""; cmd.CommandText = query; OleDbDataAdapter da = new OleDbDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); dataGridView1.DataSource = dt; conn.Close(); } catch (Exception ex) { MessageBox.Show("erorr" + ex);}} Example 4: Program to search data from a table using VB.net Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim connection As SqlConnection = New sqlconnection() connection. ConnectionString = "Data Source=PRABHU-DESKTOP; _ Initial Catalog=testDB;Integrated Security=True" connection. Open() Dim adp As SqlDataAdapter = New SqlDataAdapter _ ("select * from stud", connection) Dim ds As DataSet = New DataSet() adp. Fill(ds) DataGridView1. DataSource = ds. Tables(0) End Sub 8|Page