Mastering C# Database Programming by Jason Price ISBN:0782141838 Sybex © 2003 (665 pages) This guide will help you understand database programming as it provides focused coverage of ADO and how it relates to C#, as well as other complex topics including transactions, Windows forms, Web Forms, XML, and Web Services Table of Contents Mastering C# Database Programming Introduction Part 1 - Introduction to ADO.NET and Databases Introduction to Database Programming with ADO.NET - Introduction to Databases - Introduction to Structured Query Language (SQL) - Introduction to Transact-SQL Programming - Overview of the ADO.NET Classes - Introducing Windows Applications and ADO.NET Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Part 2 - Fundamental Database Programming with ADO.NET Chapter 7 - Connecting to a Database Chapter 8 - Executing Database Commands Chapter 9 - Using DataReader Objects to Read Results Chapter 10 - Using Dataset Objects to Store Data Chapter 11 - Using DataSet Objects to Modify Data Chapter 12 - Navigating and Modifying Related Data Chapter 13 - Using DataView Objects Part 3 - Advanced Database Programming with ADO.NET Chapter 14 - Advanced Transaction Control Chapter 15 - Introducing Web Applications—ASP.NET Chapter 16 - Using SQL Server's XML Support Chapter 17 - Web Services Index List of Figures List of Tables List of Listings List of Sidebars Back Cover C# and ADO.NET facilitate the development of a new generation of database applications, including remote applications that run on the Web Mastering C# Database Programming is the resource you need to thrive in this new world Assuming no prior experience with database programming, this book teaches you every aspect of the craft, from GUI design to server development to middle-tier implementation If you’re familiar with earlier versions of ADO, you’ll master the many new features of ADO.NET all the more quickly You’ll also learn the importance of XML within the new NET paradigm Coverage Includes Accessing a database using C# and ADO.NET Using SQL to access a database Using Visual Studio NET to build applications Creating and modifying database tables Understanding ADO.NET classes Designing, building, and deploying Web applications that access a database Designing, building, and deploying effective Web services Using SQL Server’s built-in XML capabilities Working with a database in a disconnected manner Using advanced transaction controls Using Transact-SQL to create stored procedures and functions in a SQL Server database About the Author Jason Price is an independent consultant and writer, and is both a Microsoft Certified Professional and an Oracle Certified Professional Jason has more than 10 years of experience in the software industry, and he has extensive experience with C#, NET, and Java He is the author of Mastering Visual C# NET, Oracle9i JDBC Programming, and Java Programming with Oracle SQLJ Mastering C# Database Programming Jason Price San Francisco London Associate Publisher: Joel Fugazzotto Acquisitions Editor: Denise Santoro-Lincoln Developmental Editor: Tom Cirtin Production Editor: Erica Yee Technical Editor: Acey Bunch Copyeditor: Laura Ryan Compositor: Jill Niles Graphic Illustrator: Jeff Wilson, Happenstance Type-O-Rama Proofreaders: Emily Hsuan, Laurie O'Connell, Nancy Riddiough, Monique van den Berg Indexer: Ted Laux Book Designer: Maureen Forys, Happenstance Type-O-Rama Cover Designer: Design Site Cover Illustrator: Tania Kac, Design Site Copyright © 2003 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501 World rights reserved The author created reusable code in this publication expressly for reuse by readers Sybex grants readers limited permission to reuse the code found in this publication or its accompanying CD-ROM so long as the author is attributed in any application containing the reusable code and the code itself is never distributed, posted on line by electronic transmission, sold, or commercially exploited as a stand-alone product Aside from this specific exception concerning reusable code, no part of this publication may be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic, or other record, without the prior agreement and written permission of the publisher Library of Congress Card Number: 2002116881 ISBN: 0-7821-4183-8 SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc in the United States and/or other countries Mastering and the Mastering logo are trademarks of SYBEX Inc Screen reproductions produced with FullShot 99 FullShot 99 © 19911999 Inbit Incorporated All rights reserved FullShot is a trademark of Inbit Incorporated Internet screen shot(s) using Microsoft Internet Explorer 6 reprinted by permission from Microsoft Corporation TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the manufacturer The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software whenever possible Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s) The author and the publisher make no representation or warranties of any kind with regard to the completeness or accuracy of the contents herein and accept no liability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damages of any kind caused or alleged to be caused directly or indirectly from this book Photographs and illustrations used in this book have been downloaded from publicly accessible file archives and are used in this book for news reportage purposes only to demonstrate the variety of graphics resources available via electronic access Text and images available over the Internet may be subject to copyright and other rights owned by third parties Online availability of text and images does not imply that they may be reused without the permission of rights holders, although the Copyright Act does permit certain unauthorized reuse as fair use under 17 U.S.C Section 107 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 Software License Agreement: Terms and Conditions The media and/or any online materials accompanying this book that are available now or in the future contain programs and/or text files (the "Software") to be used in connection with the book SYBEX hereby grants to you a license to use the Software, subject to the terms that follow Your purchase, acceptance, or use of the Software will constitute your acceptance of such terms The Software compilation is the property of SYBEX unless otherwise indicated and is protected by copyright to SYBEX or other copyright owner(s) as indicated in the media files (the "Owner(s)") You are hereby granted a single-user license to use the Software for your personal, noncommercial use only You may not reproduce, sell, distribute, publish, circulate, or commercially exploit the Software, or any portion thereof, without the written consent of SYBEX and the specific copyright owner(s) of any component software included on this media In the event that the Software or components include specific license requirements or end-user agreements, statements of condition, disclaimers, limitations or warranties ("End-User License"), those EndUser Licenses supersede the terms and conditions herein as to that particular Software component Your purchase, acceptance, or use of the Software will constitute your acceptance of such End-User Licenses By purchase, use, or acceptance of the Software, you further agree to comply with all export laws and regulations of the United States as such laws and regulations may exist from time to time REUSABLE CODE IN THIS BOOK The author(s) created reusable code in this publication expressly for reuse by readers Sybex grants readers limited permission to reuse the code found in this publication, its accompanying CD-ROM or available for download from our website so long as the author(s) are attributed in any application containing the reusable code and the code itself is never distributed, posted online by electronic transmission, sold, or commercially exploited as a stand-alone product SOFTWARE SUPPORT Components of the supplemental Software and any offers associated with them may be supported by the specific Owner(s) of that material, but they are not supported by SYBEX Information regarding any available support may be obtained from the Owner(s) using the information provided in the appropriate read.me files or listed elsewhere on the media Should the manufacturer(s) or other Owner(s) cease to offer support or decline to honor any offer, SYBEX bears no responsibility This notice concerning support for the Software is provided for your information only SYBEX is not the agent or principal of the Owner(s), and SYBEX is in no way responsible for providing any support for the Software, nor is it liable or responsible for any support provided, or not provided, by the Owner(s) WARRANTY SYBEX warrants the enclosed media to be free of physical defects for a period of ninety (90) days after purchase The Software is not available from SYBEX in any other form or media than that enclosed herein or posted to www.sybex.com If you discover a defect in the media during this warranty period, you may obtain a replacement of identical format at no charge by sending the defective media, postage prepaid, with proof of purchase to: SYBEX Inc Product Support Department 1151 Marina Village Parkway Alameda, CA 94501 Web: http://www.sybex.com After the 90-day period, you can obtain replacement media of identical format by sending us the defective disk, proof of purchase, and a check or money order for $10, payable to SYBEX DISCLAIMER SYBEX makes no warranty or representation, either expressed or implied, with respect to the Software or its contents, quality, performance, merchantability, or fitness for a particular purpose In no event will SYBEX, its distributors, or dealers be liable to you or any other party for direct, indirect, special, incidental, consequential, or other damages arising out of the use of or inability to use the Software or its contents even if advised of the possibility of such damage In the event that the Software includes an online update feature, SYBEX further disclaims any obligation to provide this feature for any specific duration other than the initial posting The exclusion of implied warranties is not permitted by some states Therefore, the above exclusion may not apply to you This warranty provides you with specific legal rights; there may be other rights that you may have that vary from state to state The pricing of the book with the Software by SYBEX reflects the allocation of risk and limitations on liability contained in this agreement of Terms and Conditions SHAREWARE DISTRIBUTION This Software may contain various programs that are distributed as shareware Copyright laws apply to both shareware and ordinary commercial software, and the copyright Owner(s) retains all rights If you try a shareware program and continue using it, you are expected to register it Individual programs differ on details of trial periods, registration, and payment Please observe the requirements stated in appropriate files COPY PROTECTION The Software in whole or in part may or may not be copy-protected or encrypted However, in all cases, reselling or redistributing these files without authorization is expressly forbidden except as specifically provided for by the Owner(s) therein This book is dedicated to my late mother Patricia Anne Price and to my family You're still in my heart, even though you are far away Acknowledgments Many thanks to all the great, hard-working people at Sybex-including Tom Cirtin, Denise Santoro Lincoln, Laura Ryan, and Erica Yee Chapter 7: Connecting to a Database Listing 7.1: MYSQLCONNECTION.CS Listing 7.2: CONNECTIONPOOLING.CS Listing 7.3: STATECHANGE.CS Listing 7.4: INFOMESSAGE.CS Chapter 8: Executing Database Commands Listing 8.1: EXECUTESELECT.CS Listing 8.2: SINGLEROWCOMMANDBEHAVIOR.CS Listing 8.3: SCHEMAONLYCOMMANDBEHAVIOR.CS Listing 8.4: EXECUTETABLEDIRECT.CS Listing 8.5: EXECUTESCALAR.CS Listing 8.6: EXECUTEXMLREADER.CS Listing 8.7: EXECUTEINSERTUPDATEDELETE.CS Listing 8.8: EXECUTEDDL.CS Listing 8.9: EXECUTETRANSACTION.CS Listing 8.10: USINGPARAMETERS.CS Listing 8.11: ADDPRODUCT.SQL Listing 8.12: EXECUTEADDPRODUCT.CS Listing 8.13: ADDPRODUCT2.SQL Listing 8.14: ADDPRODUCT3.SQL Listing 8.15: EXECUTEADDPRODUCT3.CS Chapter 9: Using DataReader Objects to Read Results Listing 9.1: USINGCOLUMNORDINALS.CS Listing 9.2: STRONGLYTYPEDCOLUMNVALUES.CS Listing 9.3: STRONGLYTYPEDCOLUMNVALUESSQL.CS Listing 9.4: EXECUTEMULTIPLESELECTS.CS Listing 9.5: EXECUTEMULTIPLESQL.CS Chapter 10: Using Dataset Objects to Store Data Listing 10.1: POPULATEDATASETUSINGSELECT.CS Listing 10.2: POPULATEDATASETUSINGRANGE.CS Listing 10.3: CUSTORDERHIST() STORED PROCEDURE Listing 10.4: POPULATEDATASETUSINGPROCEDURE.CS Listing 10.5: MULTIPLEDATATABLES.CS Listing 10.6: MULTIPLEDATATABLES2.CS Listing 10.7: MULTIPLEDATATABLES3.CS Listing 10.8: MERGE.CS Listing 10.9: MYXMLFILE.XML Listing 10.10: MYXMLFILE2.XML Listing 10.11: MYXMLSCHEMAFILE.XML Listing 10.12: WRITEANDREADXML.CS Listing 10.13: MAPPINGS.CS Listing 10.14: MYDATASET.XSD Chapter 11: Using DataSet Objects to Modify Data Listing 11.1: ADDRESTRICTIONS.CS Listing 11.2: FILLSCHEMA.CS Listing 11.3: FINDFILTERANDSORTDATAROWS.CS Listing 11.4: ADDPRODUCT4.SQL Listing 11.5: UPDATEPRODUCT.SQL Listing 11.6: DELETEPRODUCT.SQL Listing 11.7: DELETEPRODUCT2.SQL Chapter 12: Navigating and Modifying Related Data Listing 12.1: NESTEDXML.CS Listing 12.2: NONNESTEDXMLFILE.XML Listing 12.3: NESTEDXMLFILEL.CS Chapter 13: Using DataView Objects Listing 13.1: USINGDATAVIEW.CS Listing 13.2: FINDINGDATAROWVIEWS.CS Listing 13.3: ADDMODIFYANDREMOVEDATAROWVIEWS.CS Listing 13.4: CREATECHILDDATAVIEW.CS Listing 13.4A: USINGDATAVIEWMANAGER.CS Chapter 14: Advanced Transaction Control Listing 14.1: SAVEPOINT.SQL Listing 14.2: SAVEPOINT.CS Listing 14.3: TransactionIsolation.sql Listing 14.4: TransactionIsolation.cs Listing 14.5: Block.cs Listing 14.6: Deadlock.cs Chapter 15: Introducing Web ApplicationsASP.NET Listing 15.1: WebForm1.aspx Listing 15.2: WebForm1.aspx.cs Listing 15.3: THE WebForm1.aspx FILE Listing 15.4: THE WebForm1.aspx FILE Listing 15.5: THE WebForm1.aspx FILE Listing 15.6: CookieTest.aspx Listing 15.7: ViewStateTest.aspx Listing 15.8: SessionObjectTest.aspx Listing 15.9: ApplicationObjectTest.aspx Chapter 16: Using SQL Server's XML Support Listing 16.1: FORXMLRAW.SQL Listing 16.2: FORXMLAUTO.SQL Listing 16.3: FORXMLEXPLICIT.SQL Listing 16.4: FORXMLAUTOXMLDATA.SQL Listing 16.5: FORXMLAUTOELEMENTS.SQL Listing 16.6: FORXMLAUTOBINARYBASE64.SQL Listing 16.7: CUSTOMERS.XML Listing 16.8: CUSTOMERSWITHATTRIBUTES.XML Listing 16.9: CUSTOMERSSTYLESHEET.XSL Listing 16.10: CUSTOMERSUSINGSTYLESHEET.XML Listing 16.11: CUSTOMERSFROMCOUNTRY.SQL Listing 16.12: CUSTOMERS.XML Listing 16.13: CUSTOMERSSTYLESHEET.XSL Listing 16.14: CUSTOMERSUSINGSTYLESHEET.XML Listing 16.15: ADDCUSTOMERSXML.SQL Listing 16.16: RUNADDCUSTOMERS.SQL Listing 16.17: USINGXMLDOCUMENT.CS Listing 16.18: USINGXMLDATADOCUMENT.CS Chapter 17: Web Services Listing 17.1: CUSTOMERS.ASMX.CS Listing 17.2: CUSTOMERSWEBSERVICE.CS Listing 17.3: WEB SERVICE WSDL FILE List of Sidebars Chapter 9: Using DataReader Objects to Read Results Using Table Joins Chapter 10: Using Dataset Objects to Store Data RETRIEVING FROM MULTIPLE TABLES Chapter 11: Using DataSet Objects to Modify Data CALLING THE Fill() METHOD OF A DataAdapter MORE THAN ONCE ... SqlConnection, OleDbConnection, and OdbcConnection You use an object of the SqlConnection class to connect to a SQL Server database You use an object of the OleDbConnection class to connect to any database that supports OLE DB (Object Linking and Embedding... Step 1: Create a SqlConnection Object to Connect to the Database You use an object of the SqlConnection class to connect to a SQL Server database Step 1 in the Main() method creates a SqlConnection object named mySqlConnection to connect to the... multiple tasks in parallel), and remoting (which allows objects in one application to communicate with objects in another application) The CLR also enforces strict safety and accuracy of your executable code to ensure that no tampering occurs Framework Base Class Library The Framework Base Class