1. Trang chủ
  2. » Công Nghệ Thông Tin

Wrox beginning MySQL apr 2005 ISBN 0764579509 pdf

865 62 5

Đ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

Thông tin cơ bản

Định dạng
Số trang 865
Dung lượng 12,02 MB

Nội dung

Beginning MySQL® Robert Sheldon and Geoff Moes TEAM LinG - Live, Informative, Non-cost and Genuine ! Beginning MySQL® Published by Wiley Publishing, Inc 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2005 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 0-7645-7950-9 Manufactured in the United States of America 10 1B/RW/QT/QV/IN No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, e-mail: brandreview@wiley.com LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S at (800) 762-2974, outside the U.S at (317) 572-3993 or fax (317) 572-4002 Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available in electronic books Library of Congress Cataloging-in-Publication Data Sheldon, Robert, 1955Beginning MySQL / Robert Sheldon and Geoff Moes p cm Includes bibliographical references and indexes ISBN 0-7645-7950-9 (paper/website : alk paper) SQL (Computer program language) MySQL (Electronic resource) I Moes, Geoff, 1963- II Title QA76.3.S67S54 2005 005.75'65 dc22 2004031058 Trademarks: Wiley, the Wiley Publishing logo and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United States and other countries, and may not be used without written permission MySQL is a registered trademark of MySQL AB Limited Company All other trademarks are the property of their respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book TEAM LinG - Live, Informative, Non-cost and Genuine ! About the Authors Robert Sheldon Robert Sheldon’s MySQL programming is rooted in ten years of experience working with SQL, as it is implemented not only in a MySQL environment, but also within SQL Server, Microsoft Access, and Oracle environments He has programmed with SQL directly through database interfaces and script files and indirectly through PHP, JSP, ASP, and ASP.NET applications that connected to various databases and issued SQL statements Robert has also managed the maintenance and development of Web sites and online tools, which has included performing project analysis, developing functional specifications, and managing database and Web development He has designed and implemented various Microsoft Access, SQL Server, and MySQL databases, as well as developed and implemented a variety of Web-based solutions In all these roles, he has had to perform numerous types of ad hoc queries and modifications, build databases, create and modify database objects, create and review embedded statements, and troubleshoot system- and data-related problems In addition to having a technical and SQL background, Robert has written or co-written nine books on various network and server technologies, including two that have focused on SQL Server design and implementation, one on SQL programming (based on the SQL:1999 standard), and one on Microsoft Office Access 2003 The books that Robert has written contain training material that is designed to teach users specific skills and to test their knowledge of the material covered Having contracted as the senior developmental editor for the Microsoft certification team, he brought to these books his experience developing exam items that helped to focus readers on the skills necessary to perform specific tasks Robert has also written and edited a variety of other documentation related to SQL databases and other computer technologies He works as an independent technical consultant and writer in the Seattle area Geoff Moes Geoff Moes is a software architect and developer who has designed and implemented databases in MySQL as well as having designed and implemented software systems in PHP, Java/J2EE, and ASP.NET that have utilized MySQL databases through various database connectivity interfaces Geoff received his bachelor’s degree in Computer Science from Virginia Tech and has worked in the software industry for 18 years He specializes in software and database architecture and development as it relates to Webbased systems He has worked with several database products in addition to MySQL, including SQL Server, DB2, and Oracle He has also developed a variety of software applications that have connected to various databases using several different languages and platforms including Java J2EE/JDBC/EJB, C++/ODBC, and ASP.NET/ODBC/OLEDB Geoff’s publishing credits include “Passing Arrays Between Jscript and C++” (September 7, 2000, ASPToday.com, under WROX) and three articles published in Windows & NET Magazine (online): “Common Internet Hacker Attacks” (December 1, 1998), “Remote Web Administration, Part 2” (November 1, 1998), and “Remote Web Administration, Part 1” (October 1, 1998) Geoff works as an independent software consultant in the Washington D.C metro area When he is not in front of the keyboard, he enjoys photography, mountain biking, hiking, and international travel TEAM LinG - Live, Informative, Non-cost and Genuine ! Credits Acquisitions Editor Vice President and Publisher Debra Williams Cauley Joseph B Wikert Development Editor Project Coordinator Brian Herrmann Erin Smith Technical Editor Quality Control Technician David Mercer Brian H Walls Copy Editor Text Design and Composition Nancy Hannigan Wiley Composition Services Editorial Manager Proofreading and Indexing Mary Beth Wakefield TECHBOOKS Production Services Vice President & Executive Group Publisher Richard Swadley Acknowledgments As with any publication, too many people were involved in the development of Beginning MySQL to name them all, but we would like to acknowledge those who we worked with the closest in order to complete this project in a timely manner (and with our sanity still somewhat intact) Our special thanks goes to Debra Williams-Cauley, the acquisitions editor at John Wiley & Sons, Inc., who pulled this project together in such a professional and responsive manner And we particularly want to thank Brian Herrmann, the development editor on this book who patiently and efficiently (and pleasantly, we might add) kept this project moving forward, while always paying attention to details and answering our never-ending stream of questions We also want to acknowledge David Mercer, the technical editor, for his grasp of the subject matter and his invaluable input into the book In addition, we want to acknowledge all the editors, proofreaders, indexers, designers, illustrators, and other participants whose efforts made this book possible Finally, we want to thank our agent, Margot Maley Hutchison, at Waterside Productions, Inc., for her help in moving forward on this project and for tending to all the details TEAM LinG - Live, Informative, Non-cost and Genuine ! Contents Acknowledgments Introduction v xxv Chapter 1: Introducing the MySQL Relational Database Management System Databases and Database Management Systems What Is a Database? The Hierarchical Model The Network Model The Relational Model Database Management Systems The MySQL RDBMS The Open-Source Movement The SQL Framework What is SQL? A Brief History of SQL The Nonprocedural Nature of SQL SQL Statements Types of Execution Implementation-Specific SQL Data-Driven Applications The Application Server Connecting to a MySQL Database Creating a Data-Driven Application Summary Exercises 9 10 11 14 14 26 31 32 32 33 35 40 42 Chapter 2: Installing MySQL Getting Started Making the Preliminary Decisions Selecting Selecting Selecting Selecting a Version of MySQL a Platform to Run MySQL a MySQL Distribution Type an Edition of MySQL Downloading Distribution Files TEAM LinG - Live, Informative, Non-cost and Genuine ! 43 43 44 44 44 45 46 46 Contents Installing MySQL 48 Using RPM Files to Install MySQL on Linux Using a Tar File to Install MySQL on Linux Creating the User and Group Accounts Copying the Tar File Unpacking the Distribution File Initializing the Installation Starting the MySQL Server Installing MySQL on Windows Running the Installation Program Configuring the MySQL Server Editions of the MySQL Server Testing Your MySQL Installation Verifying Your Linux Installation Verifying Your Windows Installation Summary Exercises 51 52 53 54 55 57 57 61 64 65 65 68 70 71 Chapter 3: Working with MySQL Understanding the MySQL Directory Structure MySQL File Storage File Storage for a Linux RPM Installation File Storage for a Linux Tar Installation File Storage for a Windows Installation The Data Directory The mysql Database The Grant Tables Using the MySQL Programs Specifying Program Options Specifying Options at a Command Prompt Specifying Options in a Configuration File Server-Related Programs, Scripts, and Library Files Client Programs The mysql Utility 73 73 74 74 75 76 77 78 79 83 83 83 85 88 89 90 Using mysql in Interactive Mode Using mysql in Batch Mode 90 97 Assigning Account Passwords 100 Setting Up a Configuration File Summary Exercises vi 49 51 103 106 107 TEAM LinG - Live, Informative, Non-cost and Genuine ! Contents Chapter 4: Designing a Relational Database 109 The Relational Model Data Normalization 109 111 First Normal Form Second Normal Form Third Normal Form 111 113 115 Relationships One-to-One Relationships One-to-Many Relationships Many-to-Many Relationships Creating a Data Model Identifying Entities Normalizing Data Identifying Relationships Refining the Data Model Designing the DVDRentals Database Summary Exercises Chapter 5: Managing Databases, Tables, and Indexes 116 117 117 119 119 122 124 125 126 127 136 137 139 Managing Databases 139 Creating Databases Modifying Databases Deleting Databases 140 142 142 Managing Tables Creating Tables Creating Column Definitions Defining a Column’s Nullability Defining Default Values Defining Primary Keys Defining Auto-Increment Columns Defining Foreign Keys Defining Table Types Creating Tables in the DVDRentals Database 142 143 144 152 153 154 155 156 158 160 Modifying Tables Deleting Tables 167 169 Managing Indexes 171 Index Types Creating Indexes Defining Indexes When Creating Tables Adding Indexes to Existing Tables Removing Indexes TEAM LinG - Live, Informative, Non-cost and Genuine ! 171 172 172 175 179 vii Contents Retrieving Information About Database Objects Using SHOW Statements Using Database-Related SHOW Statements Using Table-Related SHOW Statements Using DESCRIBE Statements Summary Exercises 179 180 180 181 183 187 188 Chapter 6: Manipulating Data in a MySQL Database Inserting Data in a MySQL Database Using an INSERT Statement to Add Data Using the Alternative of the INSERT Statement Using the Alternative to Insert Data in the DVDRentals Database Using the Alternative of the INSERT Statement Using a REPLACE Statement to Add Data Using the Alternative of the REPLACE Statement Using the Alternative of the REPLACE Statement Updating Data in a MySQL Database Using an UPDATE Statement to Update a Single Table Using an UPDATE Statement to Update Joined Tables Deleting Data from a MySQL Database Using a DELETE Statement to Delete Data Deleting Data from a Single Table Deleting Data from Joined Tables Using a TRUNCATE Statement to Delete Data Summary Exercises 189 189 190 191 195 203 205 206 208 210 211 216 219 219 220 222 226 227 227 Chapter 7: Retrieving Data from a MySQL Database The SELECT Statement 229 230 Using Expressions in a SELECT Statement Using Variables in a SELECT Statement Using a SELECT Statement to Display Values 238 241 243 The SELECT Statement Options The Optional Clauses of a SELECT Statement 245 249 The The The The The WHERE Clause GROUP BY Clause HAVING Clause ORDER BY Clause LIMIT Clause Summary Exercises viii 250 254 259 261 265 267 268 TEAM LinG - Live, Informative, Non-cost and Genuine ! Contents Chapter 8: Using Operators in Your SQL Statements Creating MySQL Expressions Operator Precedence Grouping Operators Using Operators in Expressions Arithmetic Operators Comparison Operators Logical Operators Bitwise Operators Sort Operators Summary Exercises Chapter 9: Using Functions in Your SQL Statements Comparing and Converting Data Comparison Functions GREATEST() and LEAST() Functions COALESCE() and ISNULL() Functions INTERVAL() and STRCMP() Functions Control Flow Functions IF() Function IFNULL() and NULLIF() Functions CASE() Function Cast Functions Managing Different Types of Data String Functions ASCII() and ORD() Functions CHAR_LENGTH(), CHARACTER_LENGTH(), and LENGTH() Functions CHARSET() and COLLATION() Functions CONCAT() and CONCAT_WS() Functions INSTR() and LOCATE() Functions LCASE(), LOWER(), UCASE(), and UPPER() Functions LEFT() and RIGHT() Functions REPEAT() and REVERSE() Functions SUBSTRING() Function Numeric Functions CEIL(), CEILING(), and FLOOR() Functions COT() Functions MOD() Function PI() Function POW() and POWER() Functions ROUND() and TRUNCATE() Functions SQRT() Function TEAM LinG - Live, Informative, Non-cost and Genuine ! 269 269 270 271 272 272 277 291 296 302 306 306 309 310 310 310 311 312 314 314 315 316 320 322 323 323 323 324 325 325 326 327 327 328 333 333 333 334 334 334 334 335 ix Mac OS X M Mac OS X, 45 manipulating data INSERT statement foreign key tables, 199–203 lookup tables, sample, 195–198 one row at a time ( method), 203–205 people tables, sample, 198–199 rows, one or more ( method), 191–195 syntax, 190–191 performance, optimizing, 578–579 PHP from MySQL database, 623–625 REPLACE statement INSERT statement versus, 205 alternative, 207–208, 208–210 syntax, 206 alternative, 206–208 master server replication connected slave hosts, listing (SHOW SLAVE HOSTS statement), 612 resetting (RESET MASTER statement), 611 status (SHOW MASTER STATUS statement), 611–612 user account, setting up, 608–609 mathematical functions averaging values (AVG()), 350–351 date/time (ADDDATE() and DATE_ADD()), 339–340 operators, 272–277, 282 MD5() system encryption function, 359–360 memory, caching query results, 246, 580–583 MERGE table, 160 metadata, Microsoft Windows access control, 82 anonymous users, removing, 556 benefits of using, 48 configuration file, 86–88, 103, 105–106 debug edition, 46 editions, 64–65 file storage, 76 installation program, 47, 57–61 MySQL options, 44, 94 names, case-insensitivity of, 141 query and binary logging, 512–515 root account password, setting, 101 server, configuring, 61–64 testing installation, 68–70 minimum or maximum column value (MIN() and MAX()) functions, 352–353 minus sign (-), 238 minute, extracting, 345–346 model, data elements, 128 entities, identifying, 128–130 normalizing data, 130–132 refining, 133–136 relationships between tables, 132–133 module binding, 29 modulo operator (%), 272 month, day of, 344–345 826 msi file, installing MySQL from, 57–61 multibyte value of first character, identifying (ORD()), 323 multiple database backups, 594–599 multiple table data access DELETE statement joins, creating, 394–395 DELETE subqueries, 411–413 indexes, benefits of using, 563 joins, when to use, 369–370 SELECT statement joins, creating basic joins, 374–377 described, 370–371 inner joins and cross joins, 377–380 left outer joins, 386–388 natural joins, 391–392 outer joins, 385–391 right outer joins, 389–390 sample, 381–385 sample tables, 372–373 straight joins, 380–381 syntax, 371 SELECT subqueries ALL operator, 400 ANY and SOME operators, 399–400 comparison operators, 396–399 EXISTS and NOT EXISTS operators, 402–403 grouped data, 403–407 IN and NOT IN operators, 401–402 sample, 407–410 unions joining SELECT statements, 414–417 UPDATE statement joins, creating, 393–394 UPDATE subqueries, 410–411 multiplication operator (*), 272 MyISAM tables binary logging, displaying, 89 full-text index, adding, 174–175 listing, 90 syntax, 160 MySQL data-driver applications, 33–34 described, 8–9 open-source movement, version changes, highlights of, 805–806 stored procedures, 806–807 triggers, 807–808 views, 808–809 MySQL C API, 801 MySQL C++ API, 801 mysql client utility account passwords, assigning, 100 batch mode, 97–100, 600 current database, changing (use \u command), 94 described, 22–23 direct invocation, 27 discontinuing statements (clear \c command), 91–92 help command (\? or ?), 92 importing data into table LOAD DATA statement, 438–444 mysql command, 446–448 source command, 444–446 TEAM LinG - Live, Informative, Non-cost and Genuine ! interactive mode described, 90–91 example, 94–96 reloading database, 600–601 launching, 95, 96–97 programs, 97–100 prompt display (\R command), 92–93 query, executing in specified file (source \ command), 93–94 quitting (exit or quit \q), 92 SELECT statement, 25 session information (status \s command), 94 text file, saving input and output to (tee \T command), 94 MySQL Connector/J API, 802 MySQL Connector/ODBC, 802 mysql database data folder, 78–79 user grant table, 81–82 MySQL Eiffel API, 802 MySQL Perl API, 802 MySQL PHP API, 802 MySQL Python API, 802 MySQL Tcl API, 803 mysqladmin utility commands, 488–494 described, 89, 485–486 grant tables, reloading, 101 MySQLdb, 802 mysqldump command all database tables, 588–594 all databases, 595–596 individual tables, 594 specific multiple databases, 595 mysqlimport utility, 449–452 N name columns, 21, 270 conventions, normalizing data, 124–125 converting, case-sensitivity and, 141 database, displaying, 92 of day, 344–345 natural joins, 391–392 negative values, 145 NetWare system, 90 network address, converting to numeric value (INET_ATON() and INET_NTOA()), 362 network database model, 5–6 new table, copying data into, 432–435 nonnull values, returning first or status as all null (COALESCE() and ISNULL()), 311–312 nonregistered users db table, 82 Linux user table, 81 removing, 556 nontransactional tables, locking described, 479 example, 481–483 LOCK TABLES statement, 480 UNLOCK TABLES statement, 480–481 nonunique index ALTER TABLE statement, 176–177 CREATE INDEX statement, 177–178 described, 565 uses of, 173–174 normalizing data DVDRentals data model, 130–132 first normal form, 111–113 second normal form, 113–115 third normal form, 115–116 NOT IN operator, 401–402 NOT operator bitwise, 297 described, 281–282, 292 notee (\t) command, 94 NULL, 291–296 NULL operator, 278, 281 null values column, ability to handle, 152–153 columns, accepting, 152–153 as default, 153–154 natural joins, 392 outer joins, 385, 388 restricting use of, 580 NULLIF() flow control, 315 number of characters (CHAR_LENGTH() and CHARACTER_LENGTH()), string data functions, 323 number, of month, retrieving, 343 numbers column definitions, 145–148 converting, 320 network address, converting to (INET_ATON() and INET_NTOA()), 362 numeric data, maximum displayed, 145 string data from ends, returning (LEFT() and RIGHT()), 327 extracting, PHP (substr()), 624–625 first character, identifying (ASCII()), 323 numeric data functions CEIL(), CEILING(), and FLOOR(), 333 cotangent of number (COT()), 333 PI(), 334 POW() and POWER(), 334 remainder from dividing two numbers (MOD()), 334 ROUND() and TRUNCATE(), 334–335 sample, 336–339 square root SQRT(), 335 O object, database creating, 140–141 deleting, 142 modifying, 142 object variable, 670 object-relational model, 13 ODBC, 802 ODBC (Open Database Connectivity), 30, 724 OOP (object-oriented programming) C#, 724 Java, 668 TEAM LinG - Live, Informative, Non-cost and Genuine ! 827 Index OOP (object-oriented programming) opening scriptlet tag (

Ngày đăng: 20/03/2019, 11:55

TỪ KHÓA LIÊN QUAN