C sharp database programming

710 576 2
C sharp database programming

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

theo đánh giá của thầy Hoàng Hữu Việt- bộ môn hệ thống thông tin Đại học Vinh thì cuốn sách này là cuốn sách kinh điểm bao gồm những kỹ thuật lập trình về Cơ Sở Dữ Liệu hay nhất với ngôn ngữ C#

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 Chapter 1 - Introduction to Database Programming with ADO.NET Chapter 2 - Introduction to Databases Chapter 3 - Introduction to Structured Query Language (SQL) Chapter 4 - Introduction to Transact-SQL Programming Chapter 5 - Overview of the ADO.NET Classes Chapter 6 - Introducing Windows Applications and ADO.NET 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 1 List of Listings List of Sidebars 2 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 3 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 © 1991-1999 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 4 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 End-User 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 5 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. 6 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. Introduction Welcome to Mastering C# .NET Database Programming! As you might already know, . NET is poised to become the hot platform for the next wave of technology deployment. . NET's strength is that it is built from the ground up to be used in a distributed environment- in other words, an environment that consists of computers and devices connected via a network. Note The focus of this book is how you write C# programs that interact with a database. C# uses ADO.NET to interact with a database; ADO.NET is the successor to ADO. In this book, you'll learn the details of interacting with a SQL Server database. SQL Server is Microsoft's premier database software. Microsoft has pledged its commitment and resources to making .NET a pervasive component of life in our technological society-ignore .NET at your own peril. The bottom line is you need to learn .NET if you want to remain competitive in today's-and tomorrow's- marketplace. In a nutshell, .NET is a completely new framework for writing many types of applications. The applications you can write using .NET include Windows applications and Web-based applications. You can use .NET to develop systems composed of interconnected services that communicate with each other over the Internet. In addition, you can use .NET to create applications that run on devices such as handheld computers and cellular phones. Although other languages allow you to develop such applications, .NET was designed with the interconnected network in mind. The .NET Framework consists of three primary components: 7 ● Development Languages and Tools The development languages that enable you to write .NET programs include C#, Visual Basic .NET (VB .NET), and Managed C+ +. Microsoft also has a Rapid Application Development (RAD) tool called Visual Studio .NET (VS .NET) that allows you to develop programs in an integrated development environment (IDE). You'll use C# and VS .NET in this book. ● Common Language Runtime (CLR) CLR manages your running code and provides services such as memory management, thread management (which allows you to perform 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 Library is an extensive collection of code written by Microsoft that you can use in your own programs. For example, among many other functions, the Framework Base Class Library contains code that allows you to develop Windows applications, access directories and files on disk, interact with databases, and send and receive data across a network. Who Should Read This Book? This book was written for programmers who already know C#. It contains everything you need to know to master database programming with C#. No prior experience of databases is assumed, but if you already have some knowledge of database software such as SQL Server or Oracle, you'll be off to a running start. Note If you don't know C#, I recommend the book Mastering Visual C# .NET from Sybex (2002). How to Use This Book This book is divided into three parts. In Part 1, "Introduction to ADO.NET and Databases," you'll learn everything you need to know about databases. You'll also be introduced to ADO. NET, which enables your C# programs to interact with a database. In Part 2, "Fundamental Database Programming with ADO.NET," you'll learn the C# programming with ADO.NET from the ground up. In Part 3, "Advanced Database Programming with ADO.NET," you'll go beyond the basics to learn programming techniques needed by professional database developers. The following sections describe the chapters in detail. Part 1: "Introduction to ADO.NET and Databases" 8 In Chapter 1, "Introduction to Database Programming with ADO.NET," you'll see how to use ADO.NET in a C# program to interact with a database. You also learn about Microsoft's RAD tool, Visual Studio .NET. Finally, you'll see how to use the extensive documentation from Microsoft that comes with .NET and SQL Server. In Chapter 2, "Introduction to Databases," you'll learn the details of what databases are and how they are used to store information. You'll see the use of a SQL Server database named Northwind. This database contains the information for the fictitious Northwind Company, which sells food products. This database is one of the example databases that is typically installed with SQL Server. In Chapter 3, "Introduction to the Structured Query Language," you'll learn how to use the Structured Query Language (SQL) to access a database. You'll see how you use SQL to interact with the Northwind database, and how to retrieve and modify information stored in that database. In Chapter 4, "Introduction to Transact-SQL Programming," you'll be introduced to programming with Microsoft's Transact-SQL. Transact-SQL enables you to write programs that contain SQL statements, along with standard programming constructs such as variables, conditional logic, loops, procedures, and functions. In Chapter 5, "Overview of the ADO.NET Classes," you'll get an overview of the ADO.NET classes. You'll also see a C# program that connects to a database, stores the rows locally, disconnects from the database, and then reads the contents of those local rows while disconnected from the database. This ability to store a local copy of rows retrieved from the database is one of the main strengths of ADO.NET. In Chapter 6, "Introducing Windows Applications and ADO.NET," you'll be introduced to Windows applications. A Windows application takes advantage of displaying and using the mouse and keyboard for input. Windows provides graphical items such as menus, text boxes, and radio buttons so you can build a visual interface that will be easy to use. You'll see how to build Windows applications that interact with the Northwind database. Part 2: "Fundamental Database Programming with ADO.NET" In Chapter 7, "Connecting to a Database," you'll learn the details on connecting to a database. There are three Connection classes: 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 for Databases), such as Oracle or Access. You use an object of the OdbcConnection class to connect to any database that supports ODBC (Open Database Connectivity). Ultimately, all communication with a database is done through a Connection object. In Chapter 8, "Executing Database Commands," you'll learn the details on executing 9 database commands. You use a Command object to execute a SQL SELECT, INSERT, UPDATE, or DELETE statement. You can also use a Command object to call a stored procedure, or retrieve all the rows and columns from a specific table. In Chapter 9, "Using DataReader Objects to Read Results," you'll see how to use a DataReader object to read results returned from the database. You use a DataReader object to read rows retrieved from the database using a Command object. In Chapter 10, "Using DataSet Objects to Store Data," you'll learn how to use a DataSet object to store results returned from the database. DataSet objects allow you to store a copy of the tables and rows from the database, and you can work with that local copy while disconnected from the database. In Chapter 11, "Using DataSet Objects to Modify Data," you'll examine how to modify the rows in a DataSet and then push those changes to the database via a DataAdapter. In Chapter 12, "Navigating and Modifying Related Data," you'll delve into the details of how you navigate related data in tables, make changes in that data in memory, and finally push those changes to the database. In Chapter 13, "Using DataView Objects," you'll see how to use DataView objects to filter and sort rows. The advantage of a DataView is that you can bind it to a visual component in a Windows or ASP.NET application. Part 3: "Advanced Database Programming with ADO.NET" In Chapter 14, "Advanced Transaction Control," you'll delve into advanced transaction control using SQL Server and ADO.NET. In Chapter 15, "Introducing Web Applications: ASP.NET," you'll learn the basics of ASP. NET, and you'll see how to use Visual Studio .NET to create ASP.NET applications. In Chapter 16, "Using SQL Server's XML Support," you'll learn about SQL Server's extensive support for XML. You'll also see how to store XML in a C# program using XmlDocument and XmlDataDocument objects. In Chapter 17, "Web Services," you'll learn how to build a simple web service, which is a software component that may be used across the Web. For example, you could build a eb service that allows one company to send another company an order across the Web using XML. Downloading the Example Programs 10 [...]... Access database Listing 1.2: OLEDBCONNECTIONACCESS.CS /* OleDbConnectionAccess.cs illustrates how to use an OleDbConnection object to connect to an Access database 24 */ using System; using System.Data; using System.Data.OleDb; class OleDbConnectionAccess { public static void Main() { // formulate a string containing the details of the // database connection string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;"... "provider=MSDAORA;data source=ORCL;user id=SCOTT; password=TIGER"; // create an OleDbConnection object to connect to the // database, passing the connection string to the constructor OleDbConnection myOleDbConnection = new OleDbConnection(connectionString); // create an OleDbCommand object OleDbCommand myOleDbCommand = myOleDbConnection CreateCommand(); // set the CommandText property of the OleDbCommand object to //... "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=F:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb"; // create an OleDbConnection object to connect to the // database, passing the connection string to the constructor OleDbConnection myOleDbConnection = new OleDbConnection(connectionString); // create an OleDbCommand object OleDbCommand myOleDbCommand = myOleDbConnection CreateCommand(); // set the CommandText property... ADO NET Classes." Connecting to an Access Database You connect to an Access database using an OleDbConnection object-rather than a SqlConnection object-with a connection string of the following format: provider=Microsoft.Jet.OLEDB.4.0;data source=databaseFile where databaseFile is the directory and filename of your Access database Notice that you specify the provider in the connection string, which is... your code by placing the code within a try/ catch block You'll notice that the nine steps are placed within a try/catch block, with the catch block handling a SqlException object that might be thrown by the code in the try block The SqlException class is specifically for use with code that accesses a SQL Server database The following example shows how to structure a try/catch block: try { /* code that... results from an Oracle database Listing 1.3: OLEDBCONNECTIONORACLE.CS /* OleDbConnectionOracle.cs illustrates how to use an OleDbConnection object to connect to an Oracle database */ using System; using System.Data; using System.Data.OleDb; class OleDbConnectionOracle { public static void Main() { // formulate a string containing the details of the // database connection string connectionString = 27... try { // step 1: create a SqlConnection object to connect to the // SQL Server Northwind database SqlConnection mySqlConnection = new SqlConnection( "server=localhost ;database= Northwind;uid=sa;pwd=sa" ); // step 2: create a SqlCommand object SqlCommand mySqlCommand = mySqlConnection.CreateCommand (); // step 3: set the CommandText property of the SqlCommand object to // a SQL SELECT statement that... { try { // step 1: create a SqlConnection object to connect to the // SQL Server Northwind database SqlConnection mySqlConnection = new SqlConnection( "server=localhost ;database= Northwind;uid=sa;pwd=sa" ); // step 2: create a SqlCommand object SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); // step 3: set the CommandText property of the SqlCommand object to // a SQL SELECT statement that... namespace has been imported, the following example creates an OleDbConnection object, passing connectionString to the constructor: OleDbConnection myOleDbConnection = new OleDbConnection(connectionString); Listing 1.3 illustrates how to connect to an Oracle database using an OleDbConnection object and retrieve a row from the emp table Notice that you use an OleDbCommand and OleDbDataReader object to... in the try block You'll learn more about this later in the section "Handling Exceptions" after I've discussed the nine steps in the following sections 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 SQL Server . Contents Mastering C# Database Programming Introduction Part 1 - Introduction to ADO.NET and Databases Chapter 1 - Introduction to Database Programming with. Mastering C# Database Programming by Jason Price ISBN:0782141838 Sybex © 2003 (665 pages) This guide will help you understand database programming as

Ngày đăng: 14/03/2014, 17:40

Mục lục

  • main.PDF

    • Local Disk

      • Mastering C

      • introduction.PDF

        • Local Disk

          • Mastering C

          • Part 1.pdf

            • Local Disk

              • Part 1

              • Chapter 1.pdf

                • Local Disk

                  • Chapter 1

                  • Chapter 2.pdf

                    • Local Disk

                      • Chapter 2

                      • Chapter 3.pdf

                        • Local Disk

                          • Chapter 3

                          • Chapter 4.pdf

                            • Local Disk

                              • Chapter 4

                              • Chapter 5.pdf

                                • Local Disk

                                  • Chapter 5

                                  • Chapter 6.pdf

                                    • Local Disk

                                      • Chapter 6

                                      • Part 2.pdf

                                        • Local Disk

                                          • Part 2

                                          • Chapter 7.pdf

                                            • Local Disk

                                              • Chapter 7

                                              • Chapter 8.pdf

                                                • Local Disk

                                                  • Chapter 8

                                                  • Chapter 9.pdf

                                                    • Local Disk

                                                      • Chapter 9

                                                      • Chapter 10.pdf

                                                        • Local Disk

                                                          • Chapter 10

                                                          • Chapter 11.pdf

                                                            • Local Disk

                                                              • Chapter 11

                                                              • Chapter 12.pdf

                                                                • Local Disk

                                                                  • Chapter 12

                                                                  • Chapter 13.pdf

                                                                    • Local Disk

                                                                      • Chapter 13

                                                                      • Part 3.pdf

                                                                        • Local Disk

                                                                          • Part 3

                                                                          • Chapter 14.pdf

                                                                            • Local Disk

                                                                              • Chapter 14

                                                                              • Chapter 15.pdf

                                                                                • Local Disk

                                                                                  • Chapter 15

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan