Coding ADO.NET Objects: Connection, Command, DataReader.

Slides:



Advertisements
Similar presentations
Introduction to Database Processing with ADO.NET.
Advertisements

VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Authenticating Users in an ASP.NET Application. Web Site Administration Tool From VS 2008, click Website/ ASP.Net Configuration to open Web Site Administration.
Introduction to ADO.NET Programming. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB)
ASP.NET and ADO.NET. ASP.NET Server Controls Intrinsic Controls: These controls correspond to their HTML counterparts. –Ex. Textbox, listbox, button,
VB.NET Database Tools ISYS Net Applications OLE DB Provider OLE DB Data Source OLE DB Provider ODBC Data Source SQL Server Data Source SQL Server.Net.
Introduction to Structured Query Language, SQL. SQL Select Command SELECT * FROM tableName WHERE criteria;
Website Security ISYS 512. Authentication Authentication is the process that determines the identity of a user. Web.config file – node Options: –Windows.
Web Site Security ISYS 512/812. Authentication Authentication is the process that determines the identity of a user. Web.config file – node Options: –Windows:
Coding ADO.NET Objects: Connection, Command, DataReader.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and.
VB.NET Database Access ISYS 812. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
VB.NET Database Tools ISYS 573. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to Web Application Development with.Net and Web Service ISYS 350.
ASP.NET and ADO.NET. Bind the DataReader to a DataGrid Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn.
Introduction to ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database.
Coding ADO.NET Objects: Connection, Command, DataReader.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
Working with Session. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and lose their values.
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
Coding ADO.Net DataSet Objects. DataSet Object A DataSet object can hold several tables and relationships between tables. A DataSet is a set of disconnedted.
Website Security ISYS 512. Cookies Data in Cookies System.Web Which web site set the cookie Expiration date –DateTime data type –TimeSpan data type One.
Introduction to Web Service ISYS 512. Web Service XML Web Service Web services are classes that are stored on the web which can instantiate and use in.
Introduction to ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database.
ASP and HTML. Anchor Tag testAnchorTag Demo: ASPNet/ASPNETProdListSelf.ASPX.
Introduction to Structured Query Language SQL. SQL Select Command SELECT * FROM tableName WHERE criteria;
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS546.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
Introduction to ADO.Net and Visual Studio Database Tools
In C# program Before you can start using the ODBC class definitions, you will need to include the right module. using System.Data.Odbc; // ODBC definitions.
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
 It is the primary data access model for.Net applications  Next version of ADO  Can be divided into two parts ◦ Providers ◦ DataSets  Resides in System.Data.
Working with the Application Object. Session VS Application Object The Session object helps to preserve data on a per user basis. What if we want to initialize.
Website Security ISYS 512. Authentication Authentication is the process that determines the identity of a user.
Introduction to Web Service ISYS 512. Web Service XML Web Service Web services are classes that are stored on the web which can instantiate and use in.
ASP.Net and HTML. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data.
Module 3: Performing Connected Database Operations.
ADO.NET Objects – Data Providers Dr. Ron Eaglin. Requirements Visual Studio 2005 Microsoft SQL Server 2000 or 2005 –Adventure Works Database Installed.
 It is the primary data access model for.Net applications  Next version of ADO  Can be divided into two parts ◦ Providers ◦ DataSets  Resides in System.Data.
Command Object’s ExecuteNonQuery Method ISYS 512.
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
JDS – VB.NET Skill Session Fall 2004 Presented by YUHAO LIN.
Introduction to ADO.Net and VS Database Tools and Data Binding ISYS 350.
ASP.NET Binding and an Introduction to Database Queries Please use speaker notes for additional information!
Introduction to Query Language and SQL. Basic Query Language Operators Selection Projection Join Aggregates –Sum, Count, Max, Min, Avg SubTotal Calculated.
Coding ADO.NET Objects: Connection, Command, DataReader.
C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties.
C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties.
Coding ADO.Net DataSet Objects ISYS 512. DataSet Object A DataSet object can hold several tables and relationships between tables. A DataSet is a set.
Coding ADO.NET Objects: Connection, Command, DataReader.
ASP.NET Programming with C# and SQL Server First Edition
Coding ADO.NET Objects: Connection, Command, DataReader
ADO.NET Framework.
ASP.NET and ADO.NET.
Tonga Institute of Higher Education
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Coding ADO.NET Objects: Connection, Command, DataReader
Database Handling Class and Service
ASP.NET and ADO.NET.
VB Classes ISYS 512.
Working with Session and Application Objects
Introduction to ADO.NET
Command Object’s ExecuteNonQuery Method
Introduction to ADO.Net and Visual Studio Database Tools.
Presentation transcript:

Coding ADO.NET Objects: Connection, Command, DataReader

A Simplified View of ADO.Net Objects Ado.Net Data Provider Connection Adapter Command Reader Dataset Data Consumer WinForm WebForm SQL Updates Results of SQL Selects

Connection with a Connection Object A connection object represents a unique session with a data source. Property: –Connection string: string used to open a database. Data source, OLE DB provider, password, if any, security, etc. Methods: –Use the Open/Close method to open/close a connection.

Connection String Containing information about database, OLE DB provider, password, if any, security, etc. For Jet database: –="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb“ For Access 2007, 2011: –= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SalesDB2011.accdb“ For SQL Server Express –"Data Source=David-PC\sqlexpress;Initial Catalog=testSQL08;Integrated Security=True"

Connection Object Example 1 – Jet Database: –string strConn ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\\salesDB.mdb"; – OleDbConnection objConn = new OleDbConnection(strConn); –objConn.Open(); Example 2 – Access 2011: – string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; –OleDbConnection objConn = new OleDbConnection(strConn); –objConn.Open(); Object Browser: System.Data.OleDB/oledbConnection/New Basic Methods: –Open, Close –BeginTransaction

Command Object The command object allows us to execute a SQL statement. Properties: –CommandType: Text, stored procedure, tableDirect –CommandText: SQL statement, procedure name, table name –Connection –Other properties: Parameters Basic Methods: –ExecuteReader: Creates a DataReader object that contains the results of the query. –ExecuteScalar: Executes the query, and returns the first column of the first row in the result set returned by the query. Typically used to execute a SQL aggregate function such as SUM, MAX, MIN, etc. –ExecuteNonQuery: Change the data in a database without using a DataSet by executing SQL’s UPDATE, INSERT, or DELETE statements.

DataReader Object It is read-only and forward-only cursor. Basic Methods: –Read: Reads the current record and advances the pointer to the next record. It returns False if no more record in the DataReader. –Close: Closes the dataReader. Property: –HasRows – Boolean, indicates whether this System.Data.Common.DbDataReader contains one or more rows.

ExecuteReader Example string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); objConn.Open(); string strSQL = "select * from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL,objConn); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); if (objDataReader.HasRows) { MessageBox.Show("Data reader contains rows"); } else { MessageBox.Show("No row reurns"); } Note: No NEW in the Dim statement when define a dataReader object.

Import NameSpace The “using” statement must appear before all other declarations in a file and cannot appear inside a class or module declaration. –using System.Data.OleDb;

Read Records in a DataReader string Results=""; while (objDataReader.Read()==true) { Results+=objDataReader["cid"] + " " + objDataReader["Cname"] + Environment.NewLine; } textBox1.Text = Results.ToString(); Note: Use index to read a column - objDataReader[0] Note: The Read method will (1) read a record, (2) advance pointer, (3) return true/false to indicate if more records exist.

DataReader Example string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); objConn.Open(); string strSQL = "select * from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL,objConn); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); string Results=""; while (objDataReader.Read()==true) { Results += objDataReader["cid"] + " " + objDataReader["Cname"] + Environment.NewLine; } textBox1.Text = Results.ToString();

Add Items from a DataReader to a Listbox string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select cid from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader=objComm.ExecuteReader(); while (objDataReader.Read()==true) { listBox1.Items.Add(objDataReader["cid"]); // listBox1.Items.Add(objDataReader.GetString(0)); } Note1: Listbox is not bound. 2. SelectedItem

Display Selected Customer Info in Textbox private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer where cid='" + listBox1.SelectedItem + "'"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); objDataReader.Read(); textBox1.Text = objDataReader["Cname"].ToString(); textBox2.Text = objDataReader["rating"].ToString(); objConn.Close(); }

Using a Parallel ArrayList to Store Cname and Rating ArrayList –Add –Clear –Remove –IndexOf Must add this reference: –using System.Collections;

Using a Parallel ArrayList ArrayList CnameList = new ArrayList(),RatingList = new ArrayList(); private void Form1_Load(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read() == true) { listBox1.Items.Add(objDataReader["cid"]); CnameList.Add(objDataReader["cname"]); RatingList.Add(objDataReader["rating"]); } objConn.Close(); }

Use Listbox SelectedIndex private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Text = CnameList[listBox1.SelectedIndex].ToString(); textBox2.Text = RatingList[listBox1.SelectedIndex].ToString(); }

Use SQL to Retrieve Summaries string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select count(cid) as custCount from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); if (objDataReader.Read() == true) { MessageBox.Show(objDataReader["custCount"].ToString()); } objConn.Close(); Note: Alias select count(cid) as custCount

Using Command’s ExecuteScalar to Run SQL Aggregates string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select count(cid) as custCount from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); textBox1.Text = objComm.ExecuteScalar().ToString(); objConn.Close();

ExecuteScalar Example private void radioButton_CheckedChanged(object sender, EventArgs e) { string strSQL; if (radioButton1.Checked) { strSQL = "select count(pid) as prodCount from product;"; } else if (radioButton2.Checked) { strSQL = "select max(price) as maxPrice from product;"; } else { strSQL = "select min(price) as minPrice from product;"; } string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); OleDbCommand objComm = new OleDbCommand(strSQL, objConn); objConn.Open(); textBox1.Text = objComm.ExecuteScalar().ToString(); objConn.Close(); }

Testing for Null: DBNull.Value if ( objDataReader["rating"]==DBNull.Value) { textBox2.Text = "NA"; } else { textBox2.Text = objDataReader["rating"].ToString(); }

Error Handling string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select cid from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); try { objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read() == true) { listBox1.Items.Add(objDataReader["cid"]); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } objConn.Close(); Note: Where do declare objConn?

Command Object’s ExecuteNonQuery Method To run SQL: –Insert –Delete –Update The ExecuteNonQuery method also returns a value indicating the number of records affected by the SQL statement.

Use ExecuteNonQuery to Insert A New Record Create unbound text boxes to enter new customer record. string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQLInsert; strSQLInsert = "Insert into Customer values ('"; strSQLInsert += textBox1.Text + "','" + textBox2.Text + "','"; strSQLInsert += textBox3.Text + "','" + textBox4.Text + "')"; OleDbCommand objCommInsert= new OleDbCommand(strSQLInsert, objConn); objConn.Open(); MessageBox.Show(strSQLInsert.ToString()); try { objCommInsert.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message); } objConn.Close();

Use ExecuteNonQuery to Delete A New Record 1.Create a listbox with CIDs 2.Delete the selected record and remove the CID from the listbox. string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "delete from customer where cid = '" + listBox1.SelectedItem + "'"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); try { int affectedRecords; objConn.Open(); affectedRecords= objComm.ExecuteNonQuery(); MessageBox.Show(affectedRecords.ToString() + "records deleted"); listBox1.Items.RemoveAt(listBox1.SelectedIndex); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } objConn.Close();

Use ExecuteNonQuery to Update A New Record Create a project that do the following tasks: –Use a DataReader to retrieve customer IDs and populate a listbox. –Select a new rating from radio buttons for the selected customer. –Update customer’s rating using the ExecuteNonQuery method of a Command object.

create CID listbox: private void Form4_Load(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select cid from customer;"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); try { objConn.Open(); OleDbDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read() == true) { listBox1.Items.Add(objDataReader["cid"]); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } objConn.Close(); }

Update customer rating: private void button1_Click(object sender, EventArgs e) { string newRating; if (radioButton1.Checked) { newRating = "A"; } else if (radioButton2.Checked) { newRating = "B"; } else { newRating = "C"; } string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "Update customer set rating = '" + newRating + "' where cid='" + listBox1.SelectedItem + "'"; OleDbCommand objComm = new OleDbCommand(strSQL, objConn); try { objConn.Open(); objComm.ExecuteNonQuery(); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } objConn.Close(); }

Working with ODBC Data Source Enter: using System.Data.Odbc; Use: –OdbcConnection: Use DSN Example of connection string: – string strConn = "DSN=test32SQLDS"; –OdbcCommand –OdbcDataReader

using System.Data.Odbc; private void Form5_Load(object sender, EventArgs e) { string strConn = "DSN=test32SQLDS"; OdbcConnection objConn = new OdbcConnection(strConn); string strSQL = "select cid from customer;"; OdbcCommand objComm = new OdbcCommand(strSQL, objConn); try { objConn.Open(); OdbcDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read() == true) { listBox1.Items.Add(objDataReader["cid"]); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } objConn.Close(); }

Possible Database Errors SQL syntax errors Database connection not open Null Violate database constraints Referential integrity Field data type and length Primary key constraint Invalid data – database may have validation rules.

Setting a Field to Null with a Update Statement string strSQL = "Update customer set city = null where cid='" + listBox1.SelectedItem + "'";

Working with SQL Server Database Enter: using System.Data.SqlClient; Use: –SqlConnection: –Example of connection string: – string strConn = "Data Source=David- PC\\SQLEXPRESS;Initial Catalog=TestSQLServer;Integrated Security=True;Pooling=False"; –SqlCommand –SqlDataReader

Working with SQL Server Data Source private void Form5_Load(object sender, EventArgs e) { string strConn = "Data Source=David-PC\\SQLEXPRESS;Initial Catalog=TestSQLServer;Integrated Security=True;Pooling=False"; SqlConnection objConn = new SqlConnection(strConn); string strSQL = "select cid from customer;"; SqlCommand objComm = new SqlCommand(strSQL, objConn); try { objConn.Open(); SqlDataReader objDataReader; objDataReader = objComm.ExecuteReader(); while (objDataReader.Read() == true) { listBox1.Items.Add(objDataReader["cid"]); } catch (System.Exception ex) { MessageBox.Show(ex.Message); } objConn.Close(); }