this print for content only—size & color not accurate 7" x 9-1/4" / CASEBOUND / MALLOY1.0625 INCH BULK -- 544 pages -- 50# Spring Grant Allen Beginning DB2 From Novice to Professional Ev
Trang 1this print for content only—size & color not accurate 7" x 9-1/4" / CASEBOUND / MALLOY
(1.0625 INCH BULK 544 pages 50# Spring)
Grant Allen
Beginning DB2 From Novice to Professional
Everything you need to get up and running with DB2 for Linux, UNIX, and Windows
Beginning DB2: From Novice to Professional
Dear Reader,
Beginning DB2 is designed to get you up and running with DB2 quickly and
easily DB2 is IBM’s powerful, market-leading, relational database management system DB2 is available for Linux, UNIX, and Windows, and even for various mainframe environments It is available in editions appropriate for use in large data center applications, and in editions more suitable to departmental and personal applications There is even a free edition!
Using this book, you’ll learn to unleash DB2’s unparalleled performance, power, and features on your choice of platform It doesn’t matter if you’ve used
other databases or are entirely new to the field Beginning DB2: From Novice to
Professional is written to show you how to get the most out of DB2 as an
admin-istrator, developer, and web designer You’ll learn to install DB2 and its related components on Linux and Windows, and how to decide which features best match your needs You’ll learn how DB2 works with programming languages such as PHP, Java, Ruby, and C#; as well as its great facility for working with development environments such as Eclipse and Microsoft Visual Studio You’ll also learn about unique DB2 features such as pureXML and pureQuery, and how you can mix every conceivable type of data, from videos to XML, in the same DB2 database Finally, you’ll work with the core of DB2 to understand how it ticks, how it provides rock-solid stability and scalability, and how to make it perform in your next project
I’m excited to present you with this book DB2 is a robust database management system that supports the latest standards and technology, including the ability
to store XML natively Knowing DB2 has been a great help in my career, and this book is my way of giving back It is my hope to spread the word about a very good, reliable, and amazingly flexible product I hope you find as much success
in using DB2 as I have
Sincerely,Grant Allen
THE APRESS ROADMAP
Beginning Database Design SQL QueriesBeginning
Applied Mathematics for Database Administrators Date on Database:
Trang 3Grant Allen
Beginning DB2
From Novice to Professional
942XCh00CMP2 7/11/08 8:18 AM Page i
Trang 4Beginning DB2: From Novice to Professional
Copyright © 2008 by Grant Allen
All rights reserved No part of this work may be reproduced or transmitted in any form or by any means,electronic or mechanical, including photocopying, recording, or by any information storage or retrievalsystem, without the prior written permission of the copyright owner and the publisher
ISBN-13: 978-1-59059-942-6
ISBN-10: 1-59059-942-X
ISBN-13 (electronic): 978-1-4302-0548-7
ISBN-10 (electronic): 1-4302-0548-2
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book Rather than use a trademark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademarkowner, with no intention of infringement of the trademark
Lead Editor: Jonathan Gennick
Technical Reviewer: Fred Sobotka
Editorial Board: Clay Andres, Steve Anglin, Ewan Buckingham, Tony Campbell, Gary Cornell, JonathanGennick, Matthew Moodie, Joseph Ottinger, Jeffrey Pepper, Frank Pohlmann, Ben Renow-Clarke,Dominic Shakeshaft, Matt Wade, Tom Welsh
Project Manager: Kylie Johnston
Copy Editor: Nancy Sixsmith, ConText Editorial Services, Inc
Associate Production Director: Kari Brooks-Copony
Production Editor: Kelly Winquist
Compositor: Diana Van Winkle
Proofreader: Linda Seifert
Indexer: Becky Hornyak
Artist: Diana Van Winkle
Cover Designer: Kurt Krames
Manufacturing Director: Tom Debolski
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,New York, NY 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com, orvisit http://www.springeronline.com
For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA 94705 Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit
http://www.apress.com
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.eBook versions and licenses are also available for most titles For more information, reference our SpecialBulk Sales—eBook Licensing web page at http://www.apress.com/info/bulksales
The information in this book is distributed on an “as is” basis, without warranty Although every precautionhas been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to anyperson or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly bythe information contained in this work
The source code for this book is available to readers at http://www.apress.com
942XCh00CMP2 7/11/08 8:18 AM Page ii
Trang 5For Lindsay, who laughed at all the right times.
942XCh00CMP2 7/11/08 8:18 AM Page iii
Trang 6Contents at a Glance
About the Author xix
About the Technical Reviewer xxi
Acknowledgments xxiii
Introduction xxv
PART 1 ■ ■ ■ Getting Started ■ CHAPTER 1 What Is DB2 and Where Can I Get It? 3
■ CHAPTER 2 Installing DB2 for Linux and Windows 11
PART 2 ■ ■ ■ Beginning Administration with DB2 Express Edition ■ CHAPTER 3 DB2 Wizards: The Fast Path to Working with Your New Database 39
■ CHAPTER 4 Controlling Your Environment with DB2 Control Center and Command-Line Tools 63
PART 3 ■ ■ ■ Database Fundamentals with DB2 Express Edition ■ CHAPTER 5 IBM Data Studio 89
■ CHAPTER 6 SQL for DB2: Part 1 111
■ CHAPTER 7 SQL for DB2: Part 2 127
■ CHAPTER 8 Developing Functions and Stored Procedures in DB2 143
■ CHAPTER 9 Controlling Access to DB2 163
■ CHAPTER 10 Securing Data in DB2 177
■ CHAPTER 11 Using XML with DB2 195
■ CHAPTER 12 Indexes, Sequences, and Views 215
942XCh00CMP2 7/11/08 8:18 AM Page iv
Trang 7PART 4 ■ ■ ■ Programming with
DB2 Express Edition
■ CHAPTER 13 PHP with DB2 241
■ CHAPTER 14 DB2 on Rails 263
■ CHAPTER 15 DB2 Development with Microsoft Visual Studio.NET 279
■ CHAPTER 16 Developing Java Applications with DB2 301
■ CHAPTER 17 Exploring More DB2 Development Options 323
PART 5 ■ ■ ■ Ongoing Database Administration with DB2 ■ CHAPTER 18 Database Creation and Configuration 337
■ CHAPTER 19 DB2 Backup and Recovery 359
■ CHAPTER 20 Sharing Your DB2 Environment 385
■ CHAPTER 21 Moving Data in Bulk with DB2 407
■ CHAPTER 22 Working with Design 427
■ CHAPTER 23 Moving Up to More Advanced DB2 441
■ CHAPTER 24 Monitoring and Tuning DB2 Performance 459
■ INDEX 491
942XCh00CMP2 7/11/08 8:18 AM Page v
Trang 8942XCh00CMP2 7/11/08 8:18 AM Page vi
Trang 9About the Author xix
About the Technical Reviewer xxi
Acknowledgments xxiii
Introduction xxv
PART 1 ■ ■ ■ Getting Started ■ CHAPTER 1 What Is DB2 and Where Can I Get It? 3
Who Should Read This Book? 3
Why Choose DB2? 4
DB2 Has History on Its Side 4
DB2 Is at the Forefront of Database Technology Today 4
DB2 Will Be Even Bigger in the Future 4
Choosing the Right DB2 Edition For You 5
Obtaining DB2: A World of Choice 6
Summary 9
■ CHAPTER 2 Installing DB2 for Linux and Windows 11
Installing on Windows 11
Installing on Linux 11
Unpacking Installation Downloads 12
Using the DB2 9 Discovery Kit DVD 12
Checking Preinstallation Requirements 13
Memory 13
Disk 13
Users and Groups 14
Other Configuration Prerequisites 15
Proceeding with the Installation 15
Graphical Installation Under Windows and Linux 15
Command-Line Installation Under Linux 32
Uninstalling DB2 34
Reviewing Your DB2 Installation 35
Summary 35 vii
942XCh00CMP2 7/11/08 8:18 AM Page vii
Trang 10PART 2 ■ ■ ■ Beginning Administration with
DB2 Express Edition
New Database 39
DB2 First Steps 39
Launching DB2 First Steps Under Windows 40
Launching DB2 First Steps Under Linux 41
Working with DB2 First Steps 43
Creating the SAMPLE Database 45
The DB2 Control Center 47
Starting the DB2 Control Center from First Steps 47
Starting the DB2 Control Center in Other Ways 48
Selecting Your Preferred DB2 Control Center View 49
Browsing the DB2 Control Center Object Views 50
Invoking the Create Table Control Center Wizard 52
Using the DB2 Command Editor 55
Command-Line Control of Your DB2 Environment 58
Powering Up the Command Line Processor 58
Learning About the Commands 59
Connecting and Disconnecting 60
Summary 61
■ CHAPTER 4 Controlling Your Environment with DB2 Control Center and Command-Line Tools 63
Getting Started as the Right User 63
Starting and Stopping DB2 Processes 64
From the Control Center 64
From the Command Line 66
Server Components 70
DB2 Instances and the DAS Instance 70
The DB2 Governor 71
The DB2 License Server 71
The DB2 Management Service 71
The DB2 Remote Command Server 72
The DB2 Security Server 72
The DB2 Fault Monitor Coordinator 72
■C O N T E N T S
viii
942XCh00CMP2 7/11/08 8:18 AM Page viii
Trang 11Configuring and Changing Your DB2 Instances and Databases 73
Two Different Levels of Configuration 74
Configuring Your DB2 Instances from the Control Center 75
Configuring a DB2 Database from the Control Center 78
Configuring and Changing Your DB2 Instances from the CLP 79
Configuring and Changing a DB2 Database from the CLP 81
More GUI Tools to Help You Manage DB2 82
More Tools Available from the Command Line 82
The Version Information Utility: DB2LEVEL 82
The DB2 Registry Utility: DB2SET 83
The Instance Listing Utilities: DB2ILIST and DASLIST 83
The DB2 Problem Determination Tool: DB2PD 84
Summary 85
PART 3 ■ ■ ■ Database Fundamentals with DB2 Express Edition ■ CHAPTER 5 IBM Data Studio 89
Sourcing the Data Studio 90
Installation Highlights 91
Multiple Installers for Data Studio 91
The Power of Eclipse-Based IDE Installations 92
Running Data Studio 94
Starting a New Data Project 95
New Project Connection Management 97
Adding Objects to Your Project 100
New SQL Statement Wizard 100
New Stored Procedure Wizard 104
Summary 109
■ CHAPTER 6 SQL for DB2: Part 1 111
Manipulating Data with SQL 111
Using Select Statements 112
Using Insert Statements 124
Using Update Statements 125
Using Delete Statements 126
Summary 126
■C O N T E N T S ix
942XCh00CMP2 7/11/08 8:18 AM Page ix
Trang 12■ CHAPTER 7 SQL for DB2: Part 2 127
Creating and Managing DB2 Tables 127
Data Types in DB2 127
Your First Table 130
Naming DB2 Tables 131
Specifying Column Details and Constraints 132
Working with Null Data 132
Primary Key Constraints 133
Referential Constraints 134
Check Constraints 136
Disabling Constraints and Constraint Deferral 137
Automatic Value Generation for Columns 138
Specifying Table Storage Characteristics 140
Other Table Characteristics 141
Other Techniques for Table Creation 142
Summary 142
■ CHAPTER 8 Developing Functions and Stored Procedures in DB2 143
DB2 Stored Procedures 143
Creating Stored Procedures in DB2 143
Dropping Procedures 152
Managing Procedures 154
Further Reading on DB2 Stored Procedures 155
User-Defined Functions in DB2 156
Types of User-Defined Functions in DB2 156
Creating User-Defined Functions in DB2 157
Calling User-Defined Functions in DB2 159
Managing and Deleting User-Defined Functions 161
Summary 161
■ CHAPTER 9 Controlling Access to DB2 163
DB2 Building Blocks for Authentication 164
Configuring Where and When DB2 Authenticates Users 164
Choosing Your Authentication Option 167
DB2 Instance-Level Privileged Groups 168
■C O N T E N T S
x
942XCh00CMP2 7/11/08 8:18 AM Page x
Trang 13Changing Your DB2 Authentication Parameters 169
Using Control Center to Manage Authentication Parameters 170
Using DB2 CLP to Manage Authentication Parameters 172
Group Authentication Issues 173
Configuring DB2 to Use Local or Global Groups 173
64 Groups Limitation 174
Support for Windows AD Domain Features 174
Security Context of the DB2 Server 174
Summary 175
■ CHAPTER 10 Securing Data in DB2 177
Managing Authorities and Privileges in DB2 177
Preparing to Use Authorities and Privileges 177
Database-Level Authorities 177
Group Behavior in DB2 182
Roles in DB2 184
Managing Object Privileges in DB2 185
Working with Privileges on DB2 Objects 185
Granting Object Privileges to Users 187
Label-Based Access Control in DB2 190
LBAC in Action 192
Summary 194
■ CHAPTER 11 Using XML with DB2 195
Exploring XML in the Sample Database 195
Querying Your XML Data 198
Using XQuery for XML 199
Using XPath Queries for XML 204
More pureXML Features for Querying Data 207
Changing XML Data 208
Inserting XML Data 208
XML Schema Registration in DB2 210
Updating XML Data 212
Deleting XML Data 213
Summary 214
■C O N T E N T S xi
942XCh00CMP2 7/11/08 8:18 AM Page xi
Trang 14■ CHAPTER 12 Indexes, Sequences, and Views 215
Working with Indexes 215
Creating Indexes 215
Enforcing Unique Values 217
The Important Case of Foreign Keys 218
Understanding Other Index Features 219
Using Design Advisor 221
Index Wrap Up 227
Working with Sequences 228
Creating Sequences 228
Altering Sequences 230
Using Sequences 231
Sequence Wrap Up 233
Working with Views 233
Defining Views 233
Further View Options 235
View Wrap Up 237
Summary 237
PART 4 ■ ■ ■ Programming with DB2 Express Edition ■ CHAPTER 13 PHP with DB2 241
PHP and Zend Core for DB2 241
Starting an Install of Zend Core 242
Continuing the Installation 244
Post-Installation Checks 247
Developing with the IBM_DB2 PHP Extensions 248
Connecting to a Database 248
Managing IBM_DB2 PHP Connections 252
Working with Ad Hoc SQL Statements 252
Working with Prepared Statements and Stored Procedures 255
Other IBM_DB2 PHP Functions 257
Developing with the Zend Framework 258
Configuring the Zend Framework 258
Managing Connections with the Zend Framework 259
■C O N T E N T S
xii
942XCh00CMP2 7/11/08 8:18 AM Page xii
Trang 15Executing Statements Using the Zend Core Framework 260
Other Major Classes in the Zend Core Framework 262
Summary 262
■ CHAPTER 14 DB2 on Rails 263
Installing Ruby and Rails 263
Developing with Ruby, Rails, and DB2 267
Creating a Project with Rails 267
Connecting a Rails Project to DB2 268
Designing DB2 Tables in Rails 269
Executing a Migration in Ruby for DB2 271
Evolving Your DB2 Schema with Ruby on Rails 272
The Schema_Info Table for Ruby on Rails 273
Reverting to Earlier Schema Incarnations 274
Ruby on Rails Scaffolding for DB2 274
Generating the Scaffolding 275
Ruby on Rails Scaffolding in Action with DB2 275
Summary 277
■ CHAPTER 15 DB2 Development with Microsoft Visual Studio.NET 279
Installing IBM Database Add-Ins 279
Registering the IBM Data Server Provider for NET 281
Testing DB2 NET Connectivity 282
Completing the Installation 283
Testing the Database Add-Ins 283
Managing DB2 Objects 286
Creating a New DB2 View Object 287
Building the DB2 Database Project 289
Building NET Windows Applications with DB2 290
Binding DB2 Objects to Windows Controls 291
Specifying a DB2 Connection for a Windows C# Project 292
Exploring a Connection’s Related Objects 294
Building and Running the Windows Project 294
Building NET Web Applications with DB2 295
Binding DB2 Objects to Web Controls 296
Building and Running the Web Project 298
Summary 299
■C O N T E N T S xiii
942XCh00CMP2 7/11/08 8:18 AM Page xiii
Trang 16■ CHAPTER 16 Developing Java Applications with DB2 301
Writing JDBC Applications for DB2 302
JDBC Driver Types 302
Writing the First Java DB2 Application 303
Refactoring the Connection Code 305
Working with Data 307
Working with DB2 JDBC Features 309
Developing Java Stored Procedures 311
Writing the Stored Procedure Java Class 311
Deploying the Java Stored Procedure Class 312
Writing the Stored Procedure 313
Testing the Java DB2 Stored Procedure 314
Getting Started with DB2 pureQuery for Java 315
Creating a pureQuery-Enabled Project 315
Autogenerating pureQuery Java Mapping Classes 318
Examining pureQuery Results 321
Summary 322
■ CHAPTER 17 Exploring More DB2 Development Options 323
Perl 323
Installing the Perl DBI and DBD::DB2 Modules 324
Getting Connected 327
Executing SQL Statements 328
Going Further with Perl and DB2 330
Python 330
Installing the Python DB2 Driver 330
Getting Connected 332
Executing SQL Statements 332
Going Further with Python and DB2 332
Other Languages 333
C and C++ 333
COBOL 333
Rexx 333
Visual Basic and Visual Basic.NET 334
Other Samples 334
Summary 334
■C O N T E N T S
xiv
942XCh00CMP2 7/11/08 8:18 AM Page xiv
Trang 17PART 5 ■ ■ ■ Ongoing Database Administration
with DB2
■ CHAPTER 18 Database Creation and Configuration 337
Building Blocks of DB2 Databases 337
Creating DB2 Databases 338
Specifying an Alias 339
Handling Languages and Text in DB2 Databases 340
Managing Storage for the DB2 Database 342
Understanding Tablespace Use in DB2 342
Choosing the Right Tablespace Storage Management Type 343
Using System Managed Storage Tablespaces 344
Using Database Managed Storage Tablespaces 345
Tuning Initial Tablespace Parameters 346
Introducing Buffer Pools 347
Moving Beyond Database, Tablespace, and Buffer Pool Basics 348
Creating Databases with Many Options 349
Altering Databases 349
Working with Tablespaces and Buffer Pools 350
Dropping Databases 356
Summary 357
■ CHAPTER 19 DB2 Backup and Recovery 359
Why You Should Care 359
Permissions for Backup and Recovery 359
Understanding DB2 Logging 360
General Logging Principles 360
Log File Types 361
Circular Logging 361
Archive Logging 362
Infinite Logging 365
Log Housekeeping 366
DB2 Backups 366
Anatomy of a Backup 367
Taking Backups from the Control Center 368
Advanced Backup Options from the Command Line 372
■C O N T E N T S xv
942XCh00CMP2 7/11/08 8:18 AM Page xv
Trang 18Database Recovery with DB2 375
Database Recovery for Free 375
Restoring a Database from Backup 375
Roll Forward Recovery from a Backup 376
Database Recovery Using the Control Center 377
Advanced Recovery Options from the Command Line 381
Summary 383
■ CHAPTER 20 Sharing Your DB2 Environment 385
DB2 Clients on Linux and Windows 385
Using the DB2 Express-C Edition Installer 386
Using the Dedicated DB2 Client Installers 387
Deciding Which Components to Install 393
Configuring the DB2 Client for Your Database 394
The DB2 Client Configuration Assistant 394
Command-Line DB2 Client Configuration 400
Other Connectivity Options 405
DB2 Runtime Client 405
Type 4 JDBC Driver 405
Third-Party Connectivity Options 405
Summary 406
■ CHAPTER 21 Moving Data in Bulk with DB2 407
File Formats for Moving Data 407
ASCII Format 407
Delimited Format 407
Lotus 1-2-3 Worksheet Format 408
Integration Exchange Format 408
Exporting Data 408
Performing a Simple Export 409
Exporting LOBs 409
Exporting XML Objects 411
Exporting via the Control Center 412
Importing Data 414
Performing a Simple Import 414
Dealing with Import Warnings and Errors 416
Importing a Mix of New and Updated Data 418
Performing More-Complex Imports 419
Graphical Import Using the Control Center 421
■C O N T E N T S
xvi
942XCh00CMP2 7/11/08 8:18 AM Page xvi
Trang 19Loading Data with the Load Utility 423
Other Data-Movement Tools 426
Summary 426
■ CHAPTER 22 Working with Design 427
Database Design Overview 428
Statement of Requirements 429
Identification of Users and Use Cases 430
Analysis of Use Cases and Data Requirements 432
Finding Relationships in the Data 433
Building the Logical Data Model 435
Translating a Logical Model to a Physical Model 436
Building the Physical Model in DB2 436
Model Review 440
Summary 440
■ CHAPTER 23 Moving Up to More Advanced DB2 441
Using the db2look and db2move Utilities 441
Using db2look 441
Using db2move 443
Using db2look from the Control Center 445
DB2 Replication 446
Preparing for Replication 446
Configuring Replication via the Replication Center 447
Testing Replication in Action 452
Data Row Compression 454
Data Row Compression Design 455
Estimating Compression Savings 456
Compressing a Table 457
Limitations 458
Summary 458
■ CHAPTER 24 Monitoring and Tuning DB2 Performance 459
Starting with a Sensible Approach to Tuning 459
Proactive Tuning with the Configuration Advisor 460
Understanding Isolation Levels in DB2 464
Understanding Locking in DB2 464
Using DB2’s Optimistic Locking Features 466
Continuing with the Configuration Advisor 466
■C O N T E N T S xvii
942XCh00CMP2 7/11/08 8:18 AM Page xvii
Trang 20Understanding Self-Tuning Memory in DB2 468
Traditional DB2 Memory Management Model 468
Activating STMM Mode 469
Self-Tuning Memory Management Mechanics 470
Using the Memory Visualizer 471
Monitoring and Tuning Database Activity 472
Activating Monitor Switches 473
Using DB2 Event Monitors 473
Using DB2 Snapshot Monitors 478
Tuning the DB2 Optimizer with RUNSTATS 481
Automated RUNSTATS in DB2 481
Manually Running the RUNSTATS Command 484
Using the REORGCHK and REORG Utilities 485
Working with REORGCHK 485
Working with REORG 487
Summary 489
■ INDEX 491
■C O N T E N T S
xviii
942XCh00CMP2 7/11/08 8:18 AM Page xviii
Trang 21About the Author
■GRANT ALLENhas worked in the IT field for nearly 20 years, most recently as Chief Technology
Officer for a leading Australian software vendor, before taking on his current role at Google
His work has involved private enterprise, academia, and government around the
world—con-sulting on large-scale systems design, development, performance, data warehousing, content
management, and collaboration Grant is a frequent speaker at conferences and industry
events on topics such as data mining, compliance, relational databases, collaboration
tech-nologies, the business of technology, and more He is now a team leader at Google, using
database technologies to tackle problems of Google-scale and beyond
xix
942XCh00CMP2 7/11/08 8:18 AM Page xix
Trang 22942XCh00CMP2 7/11/08 8:18 AM Page xx
Trang 23About the Technical Reviewer
■FRED SOBOTKAis a database consultant with FRS Consulting He beganhis software industry career in 1990 and started using DB2 in 1996
Fred helps businesses get the most out of DB2 for Linux, UNIX, and Windows He is an award-winning IDUG speaker and the leader ofNODE, a regional DB2 users group Fred has written about DB2 for
the IDUG Solutions Journal and DB2 Magazine, and regularly updates
a DB2 blog he started in 2004 He enjoys the local coffee and bicyclepaths of Portland, Oregon, where he lives with his wife, Allison, and theirhouseplant, Hector Fred can be reached at fred@frsconsulting.com
xxi
942XCh00CMP2 7/11/08 8:18 AM Page xxi
Trang 24942XCh00CMP2 7/11/08 8:18 AM Page xxii
Trang 25Thanks to all my family and friends who supported me along the way, and kept the humor up
when it was most needed Thanks to the members of the IBM team, who have just chalked
up 25 years and make DB2 the awesome database technology it is today Amazing!
xxiii
942XCh00CMP2 7/11/08 8:18 AM Page xxiii
Trang 26942XCh00CMP2 7/11/08 8:18 AM Page xxiv
Trang 27Welcome to Beginning DB2: From Novice to Professional This book—which is all about the
DB2 relational database management system for Linux, UNIX, and Windows—is designed to
get anyone started on the road to mastering DB2 Beginning DB2 is not designed to be a
com-plete reference library for DB2; DB2 is far too large a piece of software for any one book to
cover every advanced feature and option But Beginning DB2 is designed to capture the state
of the art in DB2 capabilities and technology, presenting a comprehensive set of introductory
and gradually more advanced material to allow anyone to be up and working with DB2 in
no time
Who This Book Is For
This book is for everyone No, really! I’ll even be sending a copy to my mother Instead of
writ-ing a book just for database administrators, or database developers, or even developers of web
and desktop systems that want to use a database, I wrote Beginning DB2 to capture what you
need to work DB2 into any environment or development project Whether you’re a web
devel-oper, project manager, avid blogger, or podcasting star, Beginning DB2 will help you take your
database work to the next level
How This Book Is Structured
This book is split into five parts, each designed to help you master certain aspects of DB2:
• Part 1 deals with DB2’s heritage and shows you how to acquire and install your own
copy of DB2
• Part 2 discusses the great tools that come with DB2 out of the box
• Part 3 leaps into the wide world of Structured Query Language (SQL) and treats you to
the depth and breadth of DB2’s SQL capabilities
• Part 4 takes a tour of the fantastic developer options IBM adds to DB2 for languages
such as Ruby, PHP, Java, C#, Python, and more
• Part 5 covers the all-important administrative details that will make you a database
administrator “par excellence” with DB2
xxv
942XCh00CMP2 7/11/08 8:18 AM Page xxv
Trang 28I tried to keep the conventions in this book very simple Where a piece of code is used, it ispresented in fixed-width Courier font, such as this (working) example:
select * from sysibm.sysdummy1
For syntax descriptions and other technical elements, I use the same font for clarity, buthave endeavored to use a conversational style to discuss the meaning and use of commandsand technology This helps you reach a better understanding in a shorter period of time Moreimportantly, it also saves trees because you don’t need to buy a book that repeats the great reference material for DB2 that you can find online
Prerequisites
There are very few prerequisites you’ll need to get the most out of this book In fact, there’snothing stopping you from reading the book without installing DB2 and trying the examples
But I’ll take a wild guess that you want to do that, so you’ll need a computer with a supported
Linux distribution, such as CentOS, OpenSuSE, or the like; or Microsoft Windows XP or Vista.Exact versions and instructions on downloading the edition of DB2 suitable for you are inChapter 1 and Chapter 2
Downloading the Code
Examples and code snippets used in the book will be available in zip file format in the loads section of the Apress website (www.apress.com) The author has also set up the sitewww.beginningdb2.com, where the examples can also be obtained
Down-Contacting the Author
Any questions, comments, or errata can be sent to the author at grantondata@gmail.com, or visitthe book’s website at www.beginningdb2.com or the author’s website at www.grantondata.com
■I N T R O D U C T I O N
xxvi
942XCh00CMP2 7/11/08 8:18 AM Page xxvi
Trang 29Getting Started
P A R T 1
942XCh01CMP2 7/11/08 10:15 AM Page 1
Trang 31What Is DB2 and
Where Can I Get It?
If you’ve ever wondered how easy it would be to learn DB2, one of the world’s most mature
and powerful relational databases, the answer is this: very easy! Beginning DB2: From Novice to
Professional covers every aspect of the fundamentals of DB2 for Linux, UNIX, and Windows The
book will help you to quickly move from beginner to confident professional in using the power
of DB2 to develop desktop and web applications, manage and administer DB2 databases, and
take charge of your data as never before It quickly builds your expertise so you can tackle new
and existing software projects with the backing of IBM’s leading database technology In no time
you’ll power ahead, realizing your dreams of the next MySpace, YouTube, or Flickr
Who Should Read This Book?
Everyone! Well, nearly everyone This book is not designed to be a boring technical
disserta-tion on the internal design of DB2, the minutiae of Structured Query Language (SQL) syntax,
or the elegance of relational set theory
This book will teach you the essentials of DB2, using DB2 as the storage and processingfoundation for a range of applications that should get you thinking about what it can do for
you You’ll learn the practical side of managing DB2 and the data it hosts, you’ll feel
comfort-able and confident with database administration tasks, and you’ll know when to relax and let
the DB2 automated features do the heavy lifting for you This book also shows how easy it is to
build desktop and web-based applications such as blog hosting services, video catalogs,
dis-cussion forums, and social networking sites
So if you’re a PHP developer, a Ruby magician, keen on project management, a fabulousgraphic designer, or a budding blogger, this book will give you just the right amount of DB2 to
match your requirements
After reading this book, you’ll be able to do the following:
• Install and manage DB2 on Linux and Windows
• Easily control DB2 and its various features using the IBM-provided tools
• Quickly write useful SQL and SQL/PL commands to manage your data
• Simultaneously handle structured and unstructured data such as video, pictures, ments, and XML
docu-3
C H A P T E R 1
942XCh01CMP2 7/11/08 10:15 AM Page 3
Trang 32• Combine DB2 databases with your web and desktop applications in languages such asPython, Ruby, C#, and others
• Use the added features of DB2 to manage backups, performance, and troubleshooting
• Comfortably handle the most complex data storage and manipulation requirementswith the power of DB2
• Look forward to future developments in database capabilities with a strong grounding
in DB2
Why Choose DB2?
You might have a pressing need to store vast quantities of data You might have heard aboutthe amazing features in the latest release of DB2 Perhaps you’ve used other databases in thepast and are interested in expanding your exposure to different relational database manage-ment systems Or maybe you just like the name! Whatever the motivation, there are excellentreasons to choose DB2 for your next project or application
DB2 Has History on Its Side
The year was 1970 A brilliant man named E F “Ted” Codd wrote a seminal paper while ing at the IBM research lab in San Jose, California The paper, which was titled “A RelationalModel of Data for Large Shared Data Banks,” triggered a revolution in how people thoughtabout data, its storage, its use, and its management
work-You don’t need to read that paper to benefit from Codd’s ideas because IBM realized it had
a winner on its hands Other members of the IBM research team—Ray Boyce and Don berlin—added to Codd’s work in the following years, developing “SEQUEL,” a language forstructured English queries This evolved into the “SQL” that is now the lingua franca used withmost databases today
Cham-DB2 Is at the Forefront of Database Technology Today
With the latest release of DB2, IBM is taking DB2 into new technological territory—to the benefit
of all its users You’ll learn about all the fantastic features that DB2 9.5 offers as you read thisbook, but the most prominent technology to find its way into DB2 is the IBM “pureXML”hybrid storage technology With pureXML, DB2 can store, manage, and leverage information
in native XML form, right beside information stored in relational form If you’ve ever had towrestle with breaking down and rebuilding XML just to store it for later reference, or struggledwith not having the tools you want to manage XML and relational data on an equal footing,DB2 9.5 and pureXML are a boon (We’ll let the section on pureXML speak for itself so youwon’t think that this topic is just a marketing exercise to promote DB2.)
DB2 Will Be Even Bigger in the Future
If you have ever started working with a new piece of technology and wondered whether therewas any mileage left in it after you invested all your time and effort, you can rest easy aboutdevoting your attention to DB2 Not only does IBM release new features and versions of DB2
C H A P T E R 1 ■ W H AT I S D B 2 A N D W H E R E C A N I G E T I T ?
4
942XCh01CMP2 7/11/08 10:15 AM Page 4
Trang 33at a regular steady pace; IBM has been doing that for more than 20 years and has already given
a sneak preview of enhancements and new technologies it will make available in the
forth-coming releases after DB2 9.5
Choosing the Right DB2 Edition For You
IBM has always made sure that an edition of DB2 exists that is tailored to match any operating
environment you can imagine And that’s true more than ever with the range of DB2 version
9.5 editions now available Currently, you can choose from the following editions:
• DB2 Express-C: A fully functional version of DB2 for Microsoft Windows and Linux that
is both free to download and free to distribute with your applications! That’s right—free
IBM also has the most generous limits of any “express” edition of a commercial prise database You can even buy an IBM-backed support service, just like all the other
enter-editions The C in Express-C stands for community, and it is the community to which
IBM contributes not just the amazing features and power of DB2 but also dedicatedsupport staff on Express-C forums and input from numerous independent experts
Express-C is amazingly full-powered and brimming with features—you’ll be surprised
by how far it can take your database!
• DB2 Express edition: Like its cousin, Express-C, this version is targeted for quick
instal-lation and use It is ideal for hybrid applications that make use of reinstal-lational and XMLfeatures DB2 Express supports up to 2 CPUs and 4GB of RAM Platforms supportedinclude Linux, Windows, and Solaris x86
• DB2 Personal edition: A DB2 edition optimized for single-user operation, this edition
can be frugal with memory and other resources while providing almost all the firepowerpresent in multiuser DB2 versions
• DB2 Everyplace 9: Take DB2 with you everywhere! On your land line, PDA, cell phone, or
embedded device Perfect for distributed applications, this edition includes nization tools to keep your data in step across your applications and across the world
synchro-• DB2 Workgroup edition: This edition raises the bar again, allowing up to 4 CPUs and
16GB of RAM, and shares all the management and development tools of the DB2 range
Platform availability also expands from the DB2 Express edition to include AIX, HP/UX,and Solaris on UltraSPARC
• DB2 Enterprise edition: DB2 with no limits! Serious horsepower to match the most
demanding of applications Advanced technology bundled with the Enterprise editioninclude high-availability technology for maximum up time, multinode clustering, spe-cialized spatial data support, and more
• DB2 Enterprise Developer edition: Because even the best features should be available to
everyone to test and develop, IBM makes the Developer edition available so that youcan make the most sophisticated applications with the minimum of fuss
• DB2 Data Warehouse edition: DB2 with special features to manage truly gargantuan
data warehouses Special features include data partitioning, multidimensional ing, and query materialization technology
cluster-C H A P T E R 1 ■ W H AT I S D B 2 A N D W H E R E C A N I G E T I T ? 5
942XCh01CMP2 7/11/08 10:15 AM Page 5
Trang 34• Other members of the DB2 family: IBM is also famous for scaling DB2 all the way up to
the mainframe, giving you unlimited potential when it comes to powering your cations Related products in the DB2 family include DB2 for iSeries and DB2 for z/OS.All members of the DB2 family share a great deal of functionality and capability in common DB2 for iSeries and DB2 for z/OS versions do take advantage of some of theunique properties of their respective platforms, and there are probably few readers whohave such a system readily at hand As such, I’ll highlight in passing any important top-ics that relate to these two platforms, such as connectivity tools, but won’t delve deeplyinto their inner workings
appli-This book focuses on the most common editions of DB2 so you become familiar with asmuch of the DB2 world as possible as quickly as possible I’ll start with DB2 Express-C andshow you all its power, flexibility, and capability In the latter chapters, I’ll discuss the differ-ences you’ll find in the Workgroup and Enterprise editions, and also show you how easy it is tomove quickly and easily between versions when required
Obtaining DB2: A World of Choice
It should come as no surprise that as well as making available free editions of DB2, IBM alsomakes it incredibly easy to obtain DB2 to install and use There is no surer way to date a bookthan to include in the text a reference to a specific website You might think that other thanhttp://www.ibm.com/, IBM must regularly change the content and layout of its website as itsproducts, services and related information evolve And you’d be right But IBM doesn’t justmake one of the best database management tools available today; IBM actually understands
at a deeper level the importance of managing fluctuating data such as URLs That’s a winded way of saying that http://www.ibm.com/db2 has consistently redirected to the currentDB2 home page for the last decade or more!
long-As Figure 1-1 shows, the home page is constantly kept up to date with the latest tion on DB2 So no matter when you find yourself reading this section, you can reliably enterthat address into your web browser and be faithfully taken to IBM’s DB2 offerings almostinstantaneously (Now that I have made such a bold statement, IBM will no doubt decide toadd masses of video, audio, and as-yet-unthought-of bandwidth-hungry content to that site,and I’ll be forced to eat my words on the “instantaneous” claim.)
informa-The DB2 home page always includes a link for the DB2 download page, so you don’t have
to go digging to find the software you want Point your browser at the DB2 home page, followthe link to the download page, and you’ll see quite a few options that cover Windows, Linux,and other operating systems in both 32-bit and 64-bit forms Depending on your platform,you’ll need between 258MB to 365MB for the download I’ll cover more about the installationsteps in Chapter 2, so for now, if downloading DB2 is your preferred option, go ahead andselect the package that matches your operating system and start your download
If you are a fan of virtual machines and the flexibility they provide, you’ll see that IBM haspartnered with Novell to make available a ready-made VMware SUSE Linux package with DB2Express-C already installed, configured, and ready for use The download package for the vir-tual machine weighs in at a hefty 1.1GB, but it can be a great kick start to using DB2 in a Linuxenvironment If you choose this option, you can skip Chapter 2, but you’ll find the chapter auseful reference if you ever find yourself with questions about how your virtual machine wasput together for you
C H A P T E R 1 ■ W H AT I S D B 2 A N D W H E R E C A N I G E T I T ?
6
942XCh01CMP2 7/11/08 10:15 AM Page 6
Trang 35Figure 1-1.The IBM DB2 home page
If you can’t use the offerings on the download page for whatever reason, there are otherreadily available ways to obtain DB2 For some years, IBM has made available at no charge its
software Discovery Kit, a collection of its leading middleware products that lets anyone try out
products such as DB2 at no charge This is a great way to grab a diverse set of tools,
informa-tion, and the DB2 software itself, all in one convenient package It’s also very useful if you find
yourself at the end of an Internet connection with limited bandwidth or face steep excess
usage fees from your ISP for the available downloads on the IBM DB2 home page
The DB2 Discovery Kit is available by registering at this URL on the DB2 home page:
http://www-304.ibm.com/jct03002c/software/data/info/expresscd/
C H A P T E R 1 ■ W H AT I S D B 2 A N D W H E R E C A N I G E T I T ? 7
942XCh01CMP2 7/11/08 10:15 AM Page 7
Trang 36Because this URL is likely to change over time, using the built-in search functionality on
the DB2 home page and entering DB2 Discovery Kit returns the page as one of the first search
results The current version of the signup page can be seen in Figure 1-2
Figure 1-2.Ordering the DB2 Discovery Kit
IBM has even thought of those of you who can’t get to their website to obtain DB2 Youcan e-mail or telephone IBM’s DB2 team to arrange to have the Discovery Kit shipped to you
C H A P T E R 1 ■ W H AT I S D B 2 A N D W H E R E C A N I G E T I T ?
8
942XCh01CMP2 7/11/08 10:15 AM Page 8
Trang 37NAMING CURRENT AND FUTURE VERSIONS OF DB2
IBM’s current release of DB2 for Linux, UNIX, and Windows is DB2 9.5 You might also hear about DB2 Viper
and wonder how it is related DB2 Viper was the code name that IBM used during the development phase for DB2 9, and DB2 Viper 2 was the code name that IBM used for DB2 9.5 So essentially, they are the same
product—one is the beta form; the other is the final released form
This style of code name has been used previously with DB2 DB2 version 8.2 was code named Stinger,and I’m sure IBM will use the same nomenclature for the next release of DB2 10 and later versions in the future
The content presented in this book is designed to be applicable for current and future versions of DB2,
so the fundamentals presented here will equip you to work with it, no matter whether you’re reading thisbook now or sometime in the future when DB2 10, or an even later version has been released
Summary
You now know all about the background of DB2, its history, and its tailor-made editions that
are available to you to suit every conceivable data management requirement If you haven’t
already got your hands on a copy of DB2 Express-C, jump to the website, telephone, or even
use good old snail mail to get your copy now The next chapter launches you right in to
installing and using DB2
C H A P T E R 1 ■ W H AT I S D B 2 A N D W H E R E C A N I G E T I T ? 9
942XCh01CMP2 7/11/08 10:15 AM Page 9
Trang 38942XCh01CMP2 7/11/08 10:15 AM Page 10
Trang 39Installing DB2 for
Linux and Windows
As you’d expect from a sophisticated product such as DB2, there are a wealth of options
available during installation from which to choose Although you’re often well served by the
default selection, if you’re like me you always want to know what you might be missing In this
chapter, you’ll step through the process of installing DB2 on both Microsoft Windows and
Linux, and examine the options presented along the way
Installing on Windows
I chose Windows XP with Service Pack 2 (SP2) for the Windows example because it will be very
familiar to many readers However, IBM supports DB2 on many Windows variants:
• Windows 2000
• Windows XP Professional, SP1 or later
• Windows Server 2003, SP1 or later
• Windows Vista
At the time of writing, Windows Vista (in its many editions) has just been released to market IBM has moved quickly to support Windows Vista with the release of DB2 9 Fix Pack 2
This release allows the DB2 server components and most of the graphical tools to operate
normally under Windows Vista A few items, such as the DB2 Developer Workbench, do not
operate under Windows Vista at this time To check on the current state of Windows Vista
sup-port, refer to the DB2 Information Center on the DB2 homepage at http://www.ibm.com/db2
Notice that Windows 2000 in the list of supported Windows versions Although IBM doessupport DB2 9 installations on Windows 2000, upgrading to a later version of Windows is sug-
gested to ensure that your operating system is supported by Microsoft
Installing on Linux
The wealth of options offered by Linux distributions leaves you spoiled with choices in selecting
the operating system for your DB2 environment There are numerous excellent distributions
from which to choose, and if you’re anything like me, you’ll have more than one favorite
11
C H A P T E R 2
942XCh02CMP3 7/1/08 3:44 PM Page 11
Trang 40To put your mind at ease, IBM lists the following distributions as being supported:
• Novell Open Enterprise Server 9
• Red Hat Enterprise Linux (RHEL) 4
For the exercises and examples in this book, I’ll be using CentOS 4.5 on x86 hardware,which is the equivalent to RHEL 4 I’ll also refer to examples using the SUSE 10.2 virtualmachine mentioned in Chapter 1 to reassure you that no matter the distribution, DB2 usuallybehaves the same way
Unpacking Installation Downloads
If you elected to download your installation source from the IBM DB2 download website,you’ll have one (or both) of the following files:
• For Windows, you’ll have the file db2exc_95_WIN_x86.zip This is a zip file, and you canuse Windows’ built-in capabilities to extract its contents or you can use an unzip utilitysuch as 7-Zip
• For Linux, you’ll have the file db2exc_95_LNX_x86.tar.gz This is a tar archive pressed with gzip, and you can pipeline the necessary unpacking commands to extractits contents Here’s an example:
com$ gunzip db2exc_95_LNX_x86.tar.gz | tar xpvf The unpacked installer for Windows requires approximately 395MB of disk space, and thespace required to unpack the installer for Linux is about 322MB Don’t forget to allow approxi-mately twice that much space for unpacking the archive; you’ll have both the downloaded fileand its contents on disk at once
-Using the DB2 9 Discovery Kit DVD
The DB2 Discovery Kit includes versions of DB2 for both Microsoft Windows and Linux inboth 32-bit and 64-bit forms Everything you need in one package! Pop the DVD into yourcomputer; the Getting Started web page will open with a wealth of information about externalresources, partnering with IBM, downloading FAQs and examples, and more
C H A P T E R 2 ■ I N S TA L L I N G D B 2 F O R L I N U X A N D W I N D O W S
12
942XCh02CMP3 7/1/08 3:44 PM Page 12