Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 19 – Database, SQL, and ADO .NET

Similar presentations


Presentation on theme: "Chapter 19 – Database, SQL, and ADO .NET"— Presentation transcript:

1 Chapter 19 – Database, SQL, and ADO .NET
Outline Introduction Relational Database Model Relational Database Overview: Books Database Structured Query Language (SQL) Basic SELECT Query WHERE Clause ORDER BY Clause Merging Data from Multiple Tables: INNER JOIN Joining Data from Tables Authors, AuthorISBN, Titles and Publishers INSERT Statement UPDATE Statement DELETE Statement

2 Chapter 19 – Database, SQL, and ADO .NET
Outline ADO .NET Object Model Programming with ADO .NET: Extracting Information from a DBMS Connecting to and Querying an Access Data Source Querying the Books Database Programming with ADO.NET: Modifying a DBMS Reading and Writing XML Files

3 19.1 Introduction Database: Integrated collection of data
Database management system (DBMS) Provides mechanisms for storing and organizing data in a way that is consistent with database’s format Allows storage and access to database without knowledge of internal representation Relational Databases most popular Use Structured Query Language to perform queries (search) and manipulate data Programming languages need an interface to interact with relational databases

4 19.2 Relational Database Model
Logical representation of data: Relationships can be considered without concern for physical structure of data Composed of tables Rows called records Columns called fields Primary key: field that contains unique data Each record can be identified by at least one distinct value New sets made from queries called result sets

5 19.2 Relational Database Model
number name department salary location 23603 Jones 413 1100 New Jersey 24568 Kerwin 2000 34589 Larson 642 1800 Los Angeles 35761 Myers 611 1400 Orlando 47132 Neumann 9000 78321 Stephens 8500 record/row field/column primary key Fig Relational-database structure of an Employee table.

6 19.3 Relational Database Overview: Books Database
Rule of Entity Integrity: every record must have a unique value in its primary-key field Compound Primary key: when a record has a unique key based on a combination of two fields Foreign key: Field for which every entry has a unique value in another table and where the field in the other table is the primary key for that table Rule of Referential Integrity: every foreign-key field value must appear in another table’s primary-key field One to many relationship: A foreign key can appear many times in its own table, but only once as primary key in another table

7 19.3 Relational Database Overview: Books Database
department location 413 New Jersey 642 Los Angeles 611 Orlando Fig Result set formed by selecting Department and Location data from the Employee table.

8 19.3 Relational Database Overview: Books Database

9 19.3 Relational Database Overview: Books Database

10 19.3 Relational Database Overview: Books Database

11 19.3 Relational Database Overview: Books Database

12 19.3 Relational Database Overview: Books Database

13 19.3 Relational Database Overview: Books Database
Fig part 1

14 19.3 Relational Database Overview: Books Database
Fig part 2

15 19.3 Relational Database Overview: Books Database
Fig part 3

16 19.3 Relational Database Overview: Books Database
AuthorISBN authorID isbn Authors firstName lastName Publishers publisherID publisherName Titles title editionNumber copyright imageFile price 1 Fig Table relationships in Books.

17 19.4 Structured Query Language (SQL)
Used to request data (perform queries) and manipulate data

18 19.4 Structured Query Language (SQL)

19 Extracts information from one or more tables in a database Format:
19.4.1Basic Select Query Extracts information from one or more tables in a database Format: Basic: SELECT * FROM tableName Example: SELECT * FROM Authors * extracts all columns To get specific fields use a comma separated list instead of *

20 Basic Select Query

21 Used to specify certain criteria in a query Basic form: Example:
Where Clause Used to specify certain criteria in a query Basic form: SELECT * FROM tableName WHERE criteria Example: SELECT * FROM Titles WHERE copyright > 1999 Can use LIKE clause Used for pattern matching Uses wildcards *: zero or more characters take its place ?: exactly one character takes its place

22 WHERE Clause

23 WHERE Clause

24 Used to arrange results of a query
ORDER BY Clause Used to arrange results of a query Can be ascending or descending order Uses ASC and DESC respectively Example: SELECT authorID FROM Authors ORDER BY authorID ASC Can be used to sort by multiple fields

25 ORDER BY Clause

26 ORDER BY Clause

27 ORDER BY Clause

28 ORDER BY Clause

29 19.4.4 Merging Data from Multiple Tables: INNER JOIN
Merges records from multiple tables into a single record Tests for matching values in a common field General Form: SELECT * FROM table1 INNER JOIN table2 ON table1.fieldName=table2.fieldName Example: SELECT firstName, isbn FROM Authors INNER JOIN AuthorISBN ON Authors.authorID= AuthorISBN.authorID Fully-qualified names use the table name and dot operator followed by the field name

30 19.4.4 Merging Data from Multiple Tables: INNER JOIN

31 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers
Tables produced by INNER JOIN can be used as arguments for another INNER JOIN

32 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers
Join Publishers and Titles tables if the publisherID matches Join two created tables if titlesISBN matches authorsISBN Join Authors and AuthorISBN if authorID matches Sort new table by title Fig TitleAuthor query of Books database.

33 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers
Fig part 1

34 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers
Fig part 2

35 Insert Statement Inserts a new record into a table Form: INSERT INTO tableName(fieldName1) VALUES (value1) Values must match field names in order and type

36 INSERT Statement

37 UPDATE Statement Modifies data in a table Form: UPDATE tableName SET fieldName1 = value1 WHERE criteria

38 UPDATE Statement

39 DELETE Statement Removes data from a table Form: DELETE FROM tableName WHERE criteria

40 DELETE Statement

41 19.5 ADO .NET and Object Model
Provides an API for accessing database systems programmatically DataSets act as caches: Store data from source in local memory

42 19.6 Programming with ADO .NET: Extracting Information from a DBMS
Examples that demonstrate how to connect to a database, query the database and display the results of the query

43 19.6.1 Connecting to and Querying an Access Data Source
Retrieves data and stores it in a DataGrid

44 Constructor to populate dataSet1
1 // Fig : TableDisplay.cs 2 // Displays data from a database table. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 // Summary description for TableDisplay.cs. 12 public class TableDisplay : System.Windows.Forms.Form 13 { private System.Data.DataSet dataSet1; private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1; private System.Windows.Forms.DataGrid dataGrid1; private System.Data.OleDb.OleDbCommand oleDbSelectCommand1; private System.Data.OleDb.OleDbCommand oleDbInsertCommand1; private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1; private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1; private System.Data.OleDb.OleDbConnection oleDbConnection1; 22 private System.ComponentModel.Container components = null; 24 public TableDisplay() { InitializeComponent(); 28 // Fill dataSet1 with data oleDbDataAdapter1.Fill( dataSet1, "Authors" ); 31 // bind data in Users table in dataSet1 to dataGrid1 dataGrid1.SetDataBinding( dataSet1, "Authors" ); } 35 TableDisplay.cs Constructor to populate dataSet1 Call method fill to retrieve data from database associated with oleDbConnection Bind DataGrid to data source

45 Specify how oleDbDataAdapter deletes data
private void InitializeComponent() { this.dataSet1 = new System.Data.DataSet(); this.oleDbDataAdapter1 = new System.Data.OleDb.OleDbDataAdapter(); this.dataGrid1 = new System.Windows.Forms.DataGrid(); this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbInsertCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbUpdateCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbDeleteCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection(); ((System.ComponentModel.ISupportInitialize) (this.dataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize) (this.dataGrid1)).BeginInit(); this.SuspendLayout(); // // dataSet1 // this.dataSet1.DataSetName = "NewDataSet"; this.dataSet1.Locale = new System.Globalization.CultureInfo("en-US"); // // oleDbDataAdapter1 // this.oleDbDataAdapter1.DeleteCommand = this.oleDbDeleteCommand1; this.oleDbDataAdapter1.InsertCommand = this.oleDbInsertCommand1; TableDisplay.cs Specify how oleDbDataAdapter deletes data Specify how oleDbDataAdapter inserts data

46 Specify how oleDbDataAdapter selects data
this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1; this.oleDbDataAdapter1.TableMappings.AddRange( new System.Data.Common.DataTableMapping[] { new System.Data.Common.DataTableMapping( "Table", "Authors", new System.Data.Common.DataColumnMapping[] { new System.Data.Common.DataColumnMapping( "authorID", "authorID"), new System.Data.Common.DataColumnMapping( "firstName", "firstName"), new System.Data.Common.DataColumnMapping( "lastName", "lastName")})}); this.oleDbDataAdapter1.UpdateCommand = this.oleDbUpdateCommand1; // // dataGrid1 // this.dataGrid1.DataMember = ""; this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid1.Location = new System.Drawing.Point(16, 16); this.dataGrid1.Name = "dataGrid1"; this.dataGrid1.Size = new System.Drawing.Size(264, 248); this.dataGrid1.TabIndex = 0; // // oleDbSelectCommand1 // this.oleDbSelectCommand1.CommandText = "SELECT authorID, firstName, lastName FROM Authors"; this.oleDbSelectCommand1.Connection = this.oleDbConnection1; Specify how oleDbDataAdapter selects data TableDisplay.cs Specify how oleDbDataAdapter updates data

47 Set CommandText for oleDbUpdageCommand1
// // oleDbInsertCommand1 // this.oleDbInsertCommand1.CommandText = "INSERT INTO Authors(firstName, lastName) VALUES " + "(?, ?)"; this.oleDbInsertCommand1.Connection = this.oleDbConnection1; this.oleDbInsertCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter("firstName", System.Data.OleDb.OleDbType.VarWChar, 50, "firstName")); this.oleDbInsertCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter("lastName", System.Data.OleDb.OleDbType.VarWChar, 50, "lastName")); // // oleDbUpdateCommand1 // this.oleDbUpdateCommand1.CommandText = "UPDATE Authors SET firstName = ?, lastName = ? WHERE" + " (authorID = ?) AND (firstNam" + "e = ? OR ? IS NULL AND firstName IS NULL) AND " + "(lastName = ? OR ? IS NULL AND las" + "tName IS NULL)"; this.oleDbUpdateCommand1.Connection = this.oleDbConnection1; this.oleDbUpdateCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "firstName", System.Data.OleDb.OleDbType.VarWChar, , "firstName")); this.oleDbUpdateCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "lastName", TableDisplay.cs Set CommandText for oleDbUpdageCommand1 Set connection property for oleDbUpdageCommand1

48 TableDisplay.cs 138 System.Data.OleDb.OleDbType.VarWChar, 50,
"lastName")); this.oleDbUpdateCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "Original_authorID", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "authorID", System.Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "Original_firstName", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "firstName", System.Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "Original_firstName1", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "firstName", System.Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "Original_lastName", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "lastName", System.Data.DataRowVersion.Original, null)); TableDisplay.cs

49 TableDisplay.cs 172 this.oleDbUpdateCommand1.Parameters.Add(
new System.Data.OleDb.OleDbParameter( "Original_lastName1", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "lastName", System.Data.DataRowVersion.Original, null)); // // oleDbDeleteCommand1 // this.oleDbDeleteCommand1.CommandText = "DELETE FROM Authors WHERE (authorID = ?) AND " + "(firstName = ? OR ? IS NULL AND firs" + "tName IS NULL) AND (lastName = ? OR ? IS NULL AND " + "lastName IS NULL)"; this.oleDbDeleteCommand1.Connection = this.oleDbConnection1; this.oleDbDeleteCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "Original_authorID", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "authorID", System.Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "Original_firstName", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "firstName", System.Data.DataRowVersion.Original, null)); TableDisplay.cs

50 TableDisplay.cs 206 this.oleDbDeleteCommand1.Parameters.Add(
new System.Data.OleDb.OleDbParameter( "Original_firstName1", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "firstName", System.Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "Original_lastName", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "lastName", System.Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand1.Parameters.Add( new System.Data.OleDb.OleDbParameter( "Original_lastName1", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "lastName", System.Data.DataRowVersion.Original, null)); // // oleDbConnection1 // TableDisplay.cs

51 Initialize oleDbConnection, and specify path to database
this.oleDbConnection1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" + @"User ID=Admin;Data Source=C:\Books\2001\csphtp1\" + @"csphtp1_examples\ch19\Books.mdb;Mode=Share " + @"Deny None;Extended Properties="""";Jet OLEDB:" + @"System database="""";Jet OLEDB:Registry " + @"Path="""";Jet OLEDB:Database Password="""";" + @"Jet OLEDB:Engine Type=5;Jet OLEDB:Database " + @"Locking Mode=1;Jet OLEDB:Global Partial Bulk " + @"Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet " + @"OLEDB:New Database Password="""";Jet OLEDB:" + @"Create System Database=False;Jet OLEDB:Encrypt " + @"Database=False;Jet OLEDB:Don't Copy Locale on " + @"Compact=False;Jet OLEDB:Compact Without Replica " + @"Repair=False;Jet OLEDB:SFP=False"; // // TableDisplay // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 273); this.Controls.AddRange( new System.Windows.Forms.Control[] { this.dataGrid1}); this.Name = "TableDisplay"; this.Text = "TableDisplay"; ((System.ComponentModel.ISupportInitialize) (this.dataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize) (this.dataGrid1)).EndInit(); this.ResumeLayout(false); 263 Initialize oleDbConnection, and specify path to database TableDisplay.cs

52 TableDisplay.cs Program Output
} // end of InitializeComponent 265 [STAThread] static void Main() { Application.Run( new TableDisplay() ); } 271 } TableDisplay.cs Program Output

53 19.6.2 Querying the Books Database
Use SELECT statements on database and display results

54 DisplayQueryResults.cs 1 // Fig. 19.28: DisplayQueryResults.cs
2 // Displays the contents of the authors database. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 public class DisplayQueryResults : System.Windows.Forms.Form 12 { private System.Data.OleDb.OleDbConnection oleDbConnection1; private System.Data.DataSet dataSet1; private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1; private System.Data.OleDb.OleDbCommand oleDbSelectCommand1; private System.Data.OleDb.OleDbCommand oleDbInsertCommand1; private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1; private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1; private System.Windows.Forms.TextBox queryTextBox; private System.Windows.Forms.Button submitButton; private System.Windows.Forms.DataGrid dataGrid1; private System.ComponentModel.Container components = null; 24 public DisplayQueryResults() { 27 InitializeComponent(); } 30 // Visual Studio.NET generated code 32 DisplayQueryResults.cs

55 Place data from database into dataSet1
[STAThread] static void Main() { Application.Run( new DisplayQueryResults() ); } 38 // perform SQL query on data private void submitButton_Click( object sender, System.EventArgs e ) { try { // set SQL query to what user // input into queryTextBox oleDbDataAdapter1.SelectCommand.CommandText = queryTextBox.Text; 49 // clear DataSet from previous operation dataSet1.Clear(); 52 // Fill data set with information that results // from SQL query oleDbDataAdapter1.Fill( dataSet1, "Authors" ); 56 // bind DataGrid to contents of DataSet dataGrid1.SetDataBinding( dataSet1, "Authors" ); } 60 catch ( System.Data.OleDb.OleDbException oleException ) { MessageBox.Show( "Invalid query" ); } 65 } // end of submitButton_Click 67 } DisplayQueryResults.cs When user clicks submit button, assign SELECT query string to OleDbDataAdapter’s SelectCommand property Place data from database into dataSet1 Bind DataGrid to data and display results

56 DisplayQueryResults.cs Program Output

57 19.7 Programming with ADO.NET: Modifying a DBMS
Example implements an address book User can insert, locate and update records

58 AddressBook.cs 1 // Fig. 19.29: AddressBook.cs
2 // Using SQL statements to manipulate a database. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 public class AddressBook : System.Windows.Forms.Form 12 { private System.Windows.Forms.TextBox faxTextBox; private System.Windows.Forms.TextBox homeTextBox; private System.Windows.Forms.TextBox firstTextBox; private System.Windows.Forms.TextBox stateTextBox; private System.Windows.Forms.TextBox idTextBox; private System.Windows.Forms.TextBox lastTextBox; private System.Windows.Forms.TextBox postalTextBox; private System.Windows.Forms.TextBox addressTextBox; private System.Windows.Forms.TextBox cityTextBox; private System.Windows.Forms.TextBox countryTextBox; private System.Windows.Forms.TextBox TextBox; private System.Data.DataSet dataSet1; private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1; private System.Data.OleDb.OleDbCommand oleDbSelectCommand1; private System.Data.OleDb.OleDbCommand oleDbInsertCommand1; private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1; private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1; private System.Data.OleDb.OleDbConnection oleDbConnection1; private System.Windows.Forms.TextBox statusTextBox; private System.Windows.Forms.Label addressLabel; private System.Windows.Forms.Label cityLabel; private System.Windows.Forms.Label stateLabel; private System.Windows.Forms.Label idLabel; AddressBook.cs

59 Perform SELECT query on database
private System.Windows.Forms.Label firstLabel; private System.Windows.Forms.Label lastLabel; private System.Windows.Forms.Label postalLabel; private System.Windows.Forms.Label countryLabel; private System.Windows.Forms.Label Label; private System.Windows.Forms.Button clearButton; private System.Windows.Forms.Button helpButton; private System.Windows.Forms.Button findButton; private System.Windows.Forms.Button addButton; private System.Windows.Forms.Button updateButton; private System.Windows.Forms.Label faxLabel; private System.Windows.Forms.Label homeLabel; private System.ComponentModel.Container components = null; 49 public AddressBook() { InitializeComponent(); oleDbConnection1.Open(); } 55 // Visual Studio.NET generated code 57 [STAThread] static void Main() { Application.Run( new AddressBook() ); } 63 private void findButton_Click( object sender, System.EventArgs e ) { try { AddressBook.cs Perform SELECT query on database

60 Empty DataSet of prior data
if ( lastTextBox.Text != "" ) { // clear DataSet from last operation dataSet1.Clear(); 73 // create SQL query to find contact with // specified last name oleDbDataAdapter1.SelectCommand.CommandText = "SELECT * FROM addresses WHERE lastname = '" + lastTextBox.Text + "'"; 79 // fill dataSet1 with rows resulting from // query oleDbDataAdapter1.Fill( dataSet1 ); 83 // display information Display( dataSet1 ); statusTextBox.Text += "\r\nQuery successful\r\n"; } else lastTextBox.Text = "Enter last name here then press Find"; } 92 catch ( System.Data.OleDb.OleDbException oleException ) { Console.WriteLine( oleException.StackTrace ); statusTextBox.Text += oleException.ToString(); } 98 Empty DataSet of prior data AddressBook.cs Modify SQL query’s text to perform SELECT operation Fill DataSet with query results Display data in textboxes

61 Perform INSERT operation using OleDbCommand members
catch ( InvalidOperationException invalidException ) { MessageBox.Show( invalidException.Message ); } 103 } // end of findButton_Click 105 private void addButton_Click( object sender, System.EventArgs e ) { try { if ( lastTextBox.Text != "" && firstTextBox.Text != "" ) { // create SQL query to insert row oleDbDataAdapter1.InsertCommand.CommandText = "INSERT INTO addresses (" + "firstname, lastname, address, city, " + "stateorprovince, postalcode, country, " + " address, homephone, faxnumber" + ") VALUES ('" + firstTextBox.Text + "', '" + lastTextBox.Text + "', '" + addressTextBox.Text + "', '" + cityTextBox.Text + "', '" + stateTextBox.Text + "', '" + postalTextBox.Text + "', '" + countryTextBox.Text + "', '" + TextBox.Text + "', '" + homeTextBox.Text + "', '" + faxTextBox.Text + "')"; 129 // notify user that query is being sent statusTextBox.Text += "\r\nSending query: " + oleDbDataAdapter1.InsertCommand.CommandText + "\r\n" ; AddressBook.cs Perform INSERT operation using OleDbCommand members Sets CommandText property of InsertCommand to execute proper INSERT statement

62 Send inset query to perform INSERT operation
134 // send query oleDbDataAdapter1.InsertCommand.ExecuteNonQuery(); 137 statusTextBox.Text += "\r\nQuery successful\r\n"; } else statusTextBox.Text += "\r\nEnter at least first " + "and last name then press Add\r\n"; } 144 catch ( System.Data.OleDb.OleDbException oleException ) { Console.WriteLine( oleException.StackTrace ); statusTextBox.Text += oleException.ToString(); } 150 } // end of addButton_Click 152 private void updateButton_Click( object sender, System.EventArgs e ) { try { // make sure users have found record // they wish to update if ( idTextBox.Text != "" ) { // set SQL query to update all fields in // table where id number matches id // in idTextBox oleDbDataAdapter1.UpdateCommand.CommandText = "UPDATE addresses SET " + "firstname ='" + firstTextBox.Text + "', lastname='" + lastTextBox.Text + Send inset query to perform INSERT operation AddressBook.cs Perform UPDATE operation using OleDbCommand members Sets CommandText property of UpdateCommand to execute proper Update statement

63 Send update query to perform UPDATE operation
"', address='" + addressTextBox.Text + "', city='" + cityTextBox.Text + "', stateorprovince='" + stateTextBox.Text + "', postalcode='" + postalTextBox.Text + "', country='" + countryTextBox.Text + "', address='" + TextBox.Text + "', homephone='" + homeTextBox.Text + "', faxnumber='" + faxTextBox.Text + "' WHERE id=" + idTextBox.Text; 178 // notify user that query is being set statusTextBox.Text += "\r\nSending query: " + oleDbDataAdapter1.UpdateCommand.CommandText + "\r\n"; 183 // execute query oleDbDataAdapter1.UpdateCommand.ExecuteNonQuery(); 186 statusTextBox.Text += "\r\nQuery successful\r\n"; } else statusTextBox.Text += "\r\nYou may only update " + "an existing record. Use Find to locate the" + "record, then modify the information and " + "press Update.\r\n"; } 195 catch ( System.Data.OleDb.OleDbException oleException ) { Console.WriteLine( oleException.StackTrace ); statusTextBox.Text += oleException.ToString(); } 201 } // end of updateButton_Click 203 AddressBook.cs Send update query to perform UPDATE operation

64 Clear textboxes if user clicks clear AddressBook.cs
private void clearButton_Click( object sender, System.EventArgs e ) { idTextBox.Clear(); ClearTextBoxes(); } 210 private void helpButton_Click( object sender, System.EventArgs e ) { statusTextBox.AppendText( "\r\nClick Find to locate a record\r\n" + "Click Add to insert a new record.\r\n" + "Click Update to update the information in a record " "\r\nClick Clear to empty the textboxes" ); } 220 private void Display( DataSet dataSet ) { try { // get first DataTable--there always will be one DataTable dataTable = dataSet.Tables[ 0 ]; 227 if ( dataTable.Rows.Count != 0 ) { int recordNumber = ( int ) dataTable.Rows[ 0 ][ 0 ]; 231 idTextBox.Text = recordNumber.ToString(); firstTextBox.Text = ( string ) dataTable.Rows[ 0 ][ 1 ]; lastTextBox.Text = ( string ) dataTable.Rows[ 0 ][ 2 ]; addressTextBox.Text = ( string ) dataTable.Rows[ 0 ][ 3 ]; Clear textboxes if user clicks clear AddressBook.cs Display instructions if user clicks help Updates display with data acquired by query DataTable from DataSet, contains results of query Determine if query returned any rows Retrieve first field of database Retrieve the rest of the fields of database

65 AddressBook.cs 239 cityTextBox.Text =
( string ) dataTable.Rows[ 0 ][ 4 ]; stateTextBox.Text = ( string ) dataTable.Rows[ 0 ][ 5 ]; postalTextBox.Text = ( string ) dataTable.Rows[ 0 ][ 6 ]; countryTextBox.Text = ( string ) dataTable.Rows[ 0 ][ 7 ]; TextBox.Text = ( string ) dataTable.Rows[ 0 ][ 8 ]; homeTextBox.Text = ( string ) dataTable.Rows[ 0 ][ 9 ]; faxTextBox.Text = ( string ) dataTable.Rows[ 0 ][ 10 ]; } 254 else statusTextBox.Text += "\r\nNo record found\r\n"; } 258 catch( System.Data.OleDb.OleDbException oleException ) { Console.WriteLine( oleException.StackTrace ); statusTextBox.Text += oleException.ToString(); } 264 } // end Display 266 private void ClearTextBoxes() { firstTextBox.Clear(); lastTextBox.Clear(); addressTextBox.Clear(); cityTextBox.Clear(); stateTextBox.Clear(); AddressBook.cs

66 AddressBook.cs Program Output
postalTextBox.Clear(); countryTextBox.Clear(); TextBox.Clear(); homeTextBox.Clear(); faxTextBox.Clear(); } 280 } AddressBook.cs Program Output

67 AddressBook.cs Program Output

68 AddressBook.cs Program Output

69 AddressBook.cs Program Output

70 19.8 Reading and Writing XML Files
ADO.NET can convert data from data source into XML files Uses methods WriteXml, ReadXml andGetXml

71 Create connection to database
1 // Fig. 19.30 XMLWriter.cs 2 // Demonstrates generating XML from an ADO .NET DataSet. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 public class DatabaseXMLWriter : System.Windows.Forms.Form 12 { private System.Data.OleDb.OleDbConnection baseballConnection; private System.Data.OleDb.OleDbDataAdapter playersDataAdapter; private System.Data.OleDb.OleDbCommand oleDbSelectCommand1; private System.Data.OleDb.OleDbCommand oleDbInsertCommand1; private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1; private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1; private System.Data.DataSet playersDataSet; private System.Windows.Forms.DataGrid playersDataGrid; private System.Windows.Forms.Button writeButton; private System.Windows.Forms.TextBox outputTextBox; private System.ComponentModel.Container components = null; 24 public DatabaseXMLWriter() { // // Required for Windows Form Designer support // InitializeComponent(); 31 // open database connection baseballConnection.Open(); 34 XMLWriter.cs Create connection to database

72 Populate playersDataSet with data from database XMLWriter.cs
// fill DataSet with data from OleDbDataAdapter playersDataAdapter.Fill( playersDataSet, "Players" ); 37 // bind DataGrid to DataSet playersDataGrid.SetDataBinding( playersDataSet, "Players" ); 40 } 42 // Visual Studio .NET generated code 44 // main entry point for application. [STAThread] static void Main() { Application.Run( new DatabaseXMLWriter() ); } 51 // write XML representation of DataSet when button is clicked private void writeButton_Click( object sender, System.EventArgs e) { // write XML representation of DataSet to file playersDataSet.WriteXml( "Players.xml" ); 58 // display XML in TextBox outputTextBox.Text += "Writing the following XML:\n\n" + playersDataSet.GetXml() + "\n\n"; 62 } 64 } Populate playersDataSet with data from database XMLWriter.cs Bind DataGrid to DataSet to display data Create XML representation of data when user clicks button Append XML representation to textbox

73 XMLWriter.cs

74 19.8 Reading and Writing XML Documents
Fig XML document generated from DataSet in DatabaseXMLWriter.


Download ppt "Chapter 19 – Database, SQL, and ADO .NET"

Similar presentations


Ads by Google