0% found this document useful (0 votes)
12 views58 pages

MySQL and Java Developer s Guide 1st Edition Mark Matthews download

The document is a comprehensive guide on MySQL and Java development, authored by Mark Matthews and others, covering installation, JDBC, database design, and advanced functionalities. It includes chapters on using JDBC with Java applications, transaction management, and database administration. The book is published by Wiley Publishing, Inc. and is available in various digital formats.

Uploaded by

jeewanhisen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views58 pages

MySQL and Java Developer s Guide 1st Edition Mark Matthews download

The document is a comprehensive guide on MySQL and Java development, authored by Mark Matthews and others, covering installation, JDBC, database design, and advanced functionalities. It includes chapters on using JDBC with Java applications, transaction management, and database administration. The book is published by Wiley Publishing, Inc. and is available in various digital formats.

Uploaded by

jeewanhisen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

MySQL and Java Developer s Guide 1st Edition

Mark Matthews pdf download

https://ebookname.com/product/mysql-and-java-developer-s-
guide-1st-edition-mark-matthews/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Java 2 Web Developer Certification Study Guide 2nd


Edition Natalie Levi

https://ebookname.com/product/java-2-web-developer-certification-
study-guide-2nd-edition-natalie-levi/

Splunk Developer s Guide Second Edition Smith

https://ebookname.com/product/splunk-developer-s-guide-second-
edition-smith/

Programming Java 2 Micro Edition for Symbian OS A


developer s guide to MIDP 2 0 Martin De Jode

https://ebookname.com/product/programming-java-2-micro-edition-
for-symbian-os-a-developer-s-guide-to-midp-2-0-martin-de-jode/

Immune Dysfunction and Immunotherapy in Heart Disease


1st Edition Ronald Ross Watson

https://ebookname.com/product/immune-dysfunction-and-
immunotherapy-in-heart-disease-1st-edition-ronald-ross-watson/
Marx s Revenge The Resurgence of Capitalism and the
Death of Statist Socialism 1st Edition Meghnad Desai

https://ebookname.com/product/marx-s-revenge-the-resurgence-of-
capitalism-and-the-death-of-statist-socialism-1st-edition-
meghnad-desai/

Clean Coal 1st Edition Klaes G. Douwe

https://ebookname.com/product/clean-coal-1st-edition-klaes-g-
douwe/

The Healing Code 6 Minutes to Heal the Source of Your


Health Success or Relationship Issue 1st Edition Loyd

https://ebookname.com/product/the-healing-code-6-minutes-to-heal-
the-source-of-your-health-success-or-relationship-issue-1st-
edition-loyd/

A Little Book of Language 1st Edition David Crystal

https://ebookname.com/product/a-little-book-of-language-1st-
edition-david-crystal/

Urogenital Imaging Direct Diagnosis in Radiology DX


Direct Direct Diagnosis in Radiology 1st Edition Hamm

https://ebookname.com/product/urogenital-imaging-direct-
diagnosis-in-radiology-dx-direct-direct-diagnosis-in-
radiology-1st-edition-hamm/
First Mothers Bonnie Angelo

https://ebookname.com/product/first-mothers-bonnie-angelo/
MySQL and Java
Developer’s Guide

Mark Matthews
Jim Cole
Joseph D. Gradecki
Publisher: Robert Ipsen Copyeditor: Elizabeth Welch
Editor: Robert M. Elliott Proofreader: Nancy Sixsmith
Managing Editor: Vincent Kunkemueller Compositor: Gina Rexrode
Book Producer: Ryan Publishing Group, Inc.

Designations used by companies to distinguish their products are often claimed as trademarks. In all instances
where Wiley Publishing, Inc., is aware of a claim, the product names appear in initial capital or ALL CAPITAL
LETTERS. Readers, however, should contact the appropriate companies for more complete information regarding
trademarks and registration.

This book is printed on acid-free paper. ∞

Copyright © 2003 by Wiley Publishing, Inc. All rights reserved.

Published by Wiley Publishing, Inc., Indianapolis, Indiana

Published simultaneously in Canada.

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
Section 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,
Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470. 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-4447, E-mail: [email protected].

Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing
this book, they make no representations or warranties with respect to the accuracy or completeness of the
contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particu-
lar purpose. No warranty may be created or extended by sales representatives or written sales materials. The
advice and strategies contained herein may not be suitable for your situation. You should consult with a profes-
sional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other
commercial damages, including but not limited to special, incidental, consequential, or other damages.

For general information on our other products and services please contact our Customer Care Department
within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

Trademarks: Wiley, the Wiley Publishing logo and related trade dress are trademarks or registered trademarks
of Wiley Publishing, Inc., in the United States and other countries, and may not be used without written permis-
sion. 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.

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:


Matthews, Mark.
MySQL and Java developer’s guide / Mark Matthews.
p. cm.
ISBN 0-471-26923-9 (PAPER/WEBSITE)
1. SQL (Computer program language) 2. Java (Computer program
language) I. Title.
A76.3.S67M38 2003
005.75’65—dc21

2002155887
Printed in the United States of America

10 9 8 7 6 5 4 3 2 1
C O N T E N TS
Acknowledgments xi

About the Authors xiii

Introduction xv

Chapter 1 An Overview of MySQL 1


Why Use an RDBMS? 2
Multiuser Access 2
Storage Transparency 2
Transactions 3
Searching, Modifying, and Analyzing Data 4
Ad Hoc Queries 5
Why Choose MySQL? 5
MySQL and JDBC 7
What’s Next 8

Chapter 2 JDBC and Connector/J 9


What Is JDBC? 9
What about ODBC? 10
Modeling Database Applications with JDBC 11
JDBC Versions 13
JDBC Driver Types 13
SQL Standards 14
Examining the JDBC Interface 15
The java.sql Package 15
The javax.sql Package 18
Understanding Connector/J 21
JDBC Support within 3.0.1 22
Obtaining JDBC Drivers 24
What’s Next 24

Chapter 3 Working with MySQL SQL 25


What Is a Database? 25
Database Models 27
Data Types 29
Designing a Database 29
Introducing MySQL SQL 32
Overview of MySQL 33
Creating Databases 34
Creating Tables 35
Inserts 39
Selects 40
SELECT Statement Extensions 42

iii
iv Contents

Updates 47
Deletes 50
Using SHOW 51
More on Tables 53
Transactions 55
Functions/Operators 56
Joins 56
NULL 59
What’s Next 59

Chapter 4 Installing MySQL, Java, and Connector/J 61


Installing MySQL 61
Linux Installation 62
Windows Installation 63
All Other Installations 63
Installing Java 64
Testing the Java Installation 64
Installing Connector/J 65
Testing the Connector/J Installation 66
What’s Next 66

Chapter 5 Using JDBC with Java Applications and Applets 67


Hello World 67
Loading the Connector/J Driver 69
Using DriverManager to Connect to a Database 69
Executing Queries Through Statement Objects 75
Using the ResultSet Object 78
Determining the Cursor Position 79
Moving the Cursor 79
Getter Methods 80
Primitive Getters 82
Closing the Objects 85
Making It Real 85
Our Main Function 88
The init() Method 89
The buildGUI() Method 89
Executing a Query with No Results 91
Deleting Database Rows 97
Updating Database Rows 99
CREATE TABLE 101
DROP TABLE 101
Disconnecting from the Database 103
Advanced ResultSet Manipulation 104
One Step Forward 113
One Step Back 114
Fast-Forward to the End 114
Contents v

Rewind to the Beginning 114


Goto Record 114
Freehand Query 115
Batches 115
Limiting Results 116
Database Warnings and Exceptions 117
What’s Next 118

Chapter 6 Achieving Advanced Connector/J Functionality with Servlets 119


Servlets 119
DataSource Connections 122
Execution Environment 123
Databases 123
PreparedStatements 124
Connecting to the Database 129
Determining the Submit Type 129
Displaying Data 130
Updating Data 132
Using Placeholders in a Loop 133
Using Placeholders in PreparedStatement 134
Using setObject/setBytes 136
Getting BLOBs 139
Joins 141
Updatable ResultSets 142
The Update Button Code 149
The Insert Button Code 150
Update Methods 152
Manipulating Date/Time Types 154
Methods for Retrieving a Value as a Date Type 155
Methods for Retrieving a Value as a Time Type 155
Methods for Retrieving a Value as a Timestamp Type 155
Handling BLOB and CLOB 156
Using Streams to Pull Data 158
Handling ENUM 159
Using Connector/J with JavaScript 161
What’s Next 163

Chapter 7 MySQL Type Mapping 165


Character Column Types 166
CHAR 166
VARCHAR 167
TINYTEXT 167
TEXT 167
MEDIUMTEXT 167
LONGTEXT 168
TINYBLOB 168
vi Contents

BLOB 168
MEDIUMBLOB 168
LONGBLOB 169
SET 169
ENUM 169
Using Character Types 169
Date and Time Column Types 171
DATE 172
TIME 172
DATETIME 172
YEAR 173
TIMESTAMP 173
Using Date and Time Types 173
Numeric Column Types 175
TINYINT 176
SMALLINT 176
MEDIUMINT 176
INT 177
BIGINT 177
FLOAT 177
DOUBLE 177
DECIMAL 178
Using Numeric Types 178
What’s Next 180

Chapter 8 Transactions and Table Locking with Connector/J 181


Understanding the Problem 181
MySQL's Transaction Table Types 182
The InnoDB Table Type 182
The BDB Table Type 184
Converting to Transactional from Nontransactional 184
Performing Transactions in MySQL 185
Using the autocommit Variable 185
Update Transactions 187
The SELECT/INSERT Transaction 190
Multiple Table Transactions 191
Foreign Key Integrity on Deletes 192
Ending a Transaction 192
Transaction Isolation 192
Dirty Reads 193
Phantom Reads 194
Nonrepeatable Reads 194
Table Locking 195
What’s Next 196
Contents vii

Chapter 9 Using Metadata 197


Using Database Metadata 197
Getting the Object 200
General Source Information 202
Feature Support 203
Data Source Limits 204
SQL Object Available 204
Transaction Support 204
The ResultSet Metadata 205
Getting Column Information 205
Other ResultSet Metadata 208
What’s Next 210

Chapter 10 Connection Pooling with Connector/J 211


What Is a Connection Pool? 212
Pooling with DataSource 213
Pooling with the DriverManager 218
DDConnectionBroker 219
What’s Next 221

Chapter 11 EJBs with MySQL 223


Multi-tier Architecture 223
Using Beans 225
EJB Types 225
The EJB Environment 226
Application Server Configuration 229
The Role of the Servlet 230
Entity Beans 230
Session Beans 234
Using the Beans 236
Adding a Query 238
Bean-Managed Persistence 240
ejbCreate() 241
ejbLoad() 242
ejbStore() 243
ejbRemove() 243
ejbFindByPrimaryKey() 244
Setter/Getter Methods 245
What’s Next 245

Chapter 12 Building a General Interface for MySQL 247


Tasks 248
SQL Exceptions 252
MySQL Connections 253
The Task Delegate 255
viii Contents

The Task Manager 255


Task Results 264
The Database Information Task 268
User Input for Tasks 270
The SQL Query Task 272
The Show Columns Task 275
The Insert Row Task 280
What’s Next 286

Chapter 13 Database Administration 287


Using the mysql Administration Application 287
Managing Users and Permissions 289
Changing Root 289
Adding Users 290
Limiting Resources 292
Configuring the Query Cache 293
Forcing a Cache 294
Understanding Log Files 294
Error Logs 295
General Logs 295
Binary Logs 296
Slow Query Logs 296
Maintaining Your Tables 296
Repairing Tables 297
Backing Up and Restoring Your Database 298
Restoring Data 301
InnoDB Table Types 302
DBD Table Types 302
What’s Next 303

Chapter 14 Performance and Tuning 305


Connector/J 3.0 Performance 305
Database Tuning 308
Server Options 308
Using RAID 309
Optimizing Tables 309
The MySQL Query Optimizer 310
Table Indexes 312
JDBC Tuning 313
Minimizing Data Requests 313
Keeping Consistent Connections 314
Handling Statements 315
Batching 316
Using Transactions and Locking 316
Defining the Architecture 317
Getting Data 317
Conclusion 318
Contents ix

Appendix A MySQL Development and Test Environments 319


Test Architecture #1 319
Test Architecture #2 320
Servlet Architecture 321
The EJB Architecture 323

Appendix B Databases and Tables 325


The accounts Database and Tables 325
The identification Database and Tables 326
Test Databases 327
Database Products 327
The Database Test 327

Appendix C The JDBC API and Connector/J 329


The java.sql Package 330
Array 331
BatchUpdateException 332
Blob 332
CallableStatement 333
Clob 335
Connection 335
DataTruncation 337
DatabaseMetaData 337
Date 343
Driver 343
DriverManager 343
DriverPropertyInfo 344
ParameterMetaData 344
PreparedStatement 345
Ref 346
ResultSet 347
ResultSetMetaData 350
Savepoint 351
SQLData 351
SQLException 352
SQLInput 352
SQLOutput 353
SQLPermission 353
SQLWarning 354
Statement 354
Struct 355
Time 356
Timestamp 356
Types 357
x Contents

The javax.sql Package 358


ConnectionEvent 359
ConnectionEventListener 359
ConnectionPoolDataSource 359
DataSource 360
PooledConnection 360
RowSet 360
RowSetEvent 362
RowSetInternal 362
RowSetListener 363
RowSetMetaData 363
RowSetReader 363
RowSetWriter 364
XAConnection 364
XADataSource 364

Appendix D MySQL Functions and Operators 367


Arithmetic Functions/Operators 369
Comparison Functions/Operators 372
Logical Operators 375
Control Functions 377
String Functions/Operators 379
Grouping Functions 384
Date and Time Functions 386
Other Functions 394

Appendix E Connector/J Late-Breaking Additions 397


Failover Support 397
Windows Named Pipes 398
Batch Processing Error Continuation 398
Strict Updates 399
Profile SQL 399
SSL 399

Index 401
A C K N O W L E D G M E N TS

Dedication
To my wife Diane, for all her support in my "geeky" endeavors, and to our
new daughter Lauren.
I would also like to dedicate this work to Monty, David, and the rest of the
fine group of developers at MySQL AB. Without their contribution to the
software community and dedication to free software and open source ideals,
this book would not have been possible.
--Mark Matthews

I would like to dedicate this book to my parents. Their ever-present love and
encouragement have made so many things possible.
—Jim Cole

This book is dedicated to the trinity: God, Jesus Christ, and the Holy Spirit.
—Joseph D. Gradecki

Acknowledgments
I need to acknowledge the patience and support of my beautiful and loving wife
and our boys. Thank you for the opportunity to be your husband and father.
Tim, thank you for the opportunities. Jim, welcome to this new adventure and I
look forward to many more in the future. Thank you to Liz Welch for the excel-
lent review.

xi
A B O U T T H E CAOUNTTHEO
NRTS

Mark Matthews is the creator of Connector/J and its predecessor MM.MySQL,


the Java JDBC driver for MySQL. Last year, he joined MySQL AB to further
develop Java support in MySQL. Mark specializes in Java, MySQL, XML, and
DHTML solutions and has architected major Web applications projects, includ-
ing a GIS-based retail analytics package. Mark has also taught classes in both
Java and UML.
Jim Cole is a senior software engineer specializing in Internet and knowledge
management systems. He is an active developer working in Java, C++, Perl, and
PHP. He also serves as a system administrator for several Web-based projects,
where his duties include custom software development, database management,
and security maintenance.
Joseph D. Gradecki is a software engineer at Comprehensive Software Solu-
tions, where he works on their SABIL product, an enterprise-level securities
processing system. He has built numerous dynamic, enterprise applications
using Java, AspectJ, servlets, JSPs, Resin, MySQL, BroadVision, XML, and
more. He has also built P2P distributed computing systems in a variety of lan-
guages including Java/JXTA, C/C++, and Linda. He holds Bachelors and Mas-
ters degrees in Computer Science and is currently obtaining his PhD.

xiii
Introduction

H
ave you ever been assigned a project and realized that you had no idea
how you were going to accomplish it? Many developers have experi-
enced this feeling when asked to interface their code with a database.
With a few exceptions, most developers were busy learning Lisp, linked lists,
and big-O notation during their formal education instead of learning the funda-
mentals of relationship database management systems. When the time comes
to interface their code with a database, they turn to a book like the one you are
holding.
Your challenge might be to write a Web-based system using servlets and Enter-
prise JavaBeans (EJBs) to transfer shipping records from the home office in
Bend, Oregon, to a satellite shipper in New Jersey. Or perhaps your father just
opened his new medical office and you volunteered to create a scheduling sys-
tem over the weekend.
Whatever the situation, interfacing an application to a database is one of the
most fundamental tasks a developer is required to perform. This book is
designed for developers who either have a pressing task ahead of them or who
are curious about how to read database information into their application.
By combining MySQL, the number-one open source database available, with
Java, the most portable language ever developed, you can create an undis-
putable champion. So, sit back in your desk chair with a hot chocolate and get
ready to supercharge your coding.
xvi I NTRO D U CTI O N

What’s in This Book


The primary goal of MySQL and Java Developer’s Guide is to provide a com-
prehensive approach to writing code from a Java application to a MySQL data-
base using the industry standard: JDBC. As you will see later in this
Introduction, the chapter titles indicate what area of database connectivity and
manipulation they cover. The chapters are ordered to reflect the JDBC specifi-
cation, but we aren’t here to simply describe the specification.
We wrote all of the material in the book to highlight how MySQL’s Connector/J
JDBC driver achieves the interfacing of MySQL with Java while maintaining the
spirit of the specification. With this in mind, we provide example code using all
major forms of Java development, including
■■ Applications
■■ Applets
■■ Servlets
■■ JSPs
■■ EJBs
As you work in Java and JDBC, you will see the true power of the specification.
You can write database access code in a Java application and move the code to
a servlet with little if any changes. In the case of EJBs and container-managed
persistence, we devoted a full chapter to dealing with database access without
the cumbersome details of SQL.
We designed the layout of the book to move you through the entire process of
writing Java code needed to access a back-end database. Developing the data-
base is one of the first things that you must accomplish in this process. While
we don’t delve deeply into the theory of database development, you learn how
to create databases in MySQL, administer those databases, and handle such
details as granting access permissions. From there, we take you into an exami-
nation of the MySQL Connector/J driver and how it accomplishes its goal of
portable database access. The remainder of the book steps you through Java
code that highlights how to accomplish database tasks such as the following:
■■ Querying and updating
■■ Handling ResultSets
■■ Using transactions
■■ Handling typing issues between JDBC and MySQL
■■ Working with metadata
■■ Addressing efficiency issues
MySQL and Java Developer’s Guide xvii

Once you’re familiar with these concepts, we present a complete application


that pulls it all together. Our application illustrates how you can create to a sim-
ple authorization service. Using a combination of JSP, servlets, and EJBs, the
service allows new users to create accounts, recall the account, and verify a
username/password combination. The system is designed to be interactive
using JSP pages, which are handled on the server using servlets. The JSPs can
be bypassed using the servlets directly. All of the critical information is kept on
the database for persistence and management needs.
After reading this book, you should know how to interface Java to MySQL and
be able to use the many examples for reference.

NOTE
All the code and examples in this book can be found on the the support Web site at
www.wiley.com/compbooks/matthews.

Who Should Read This Book


This book is written for Java developers who need to interface their code to a
back-end database. The book’s specifics deal with MySQL and Connector/J, but
this doesn’t limit the information because JDBC is designed to be portable
against many databases. If you aren’t using MySQL, you still find valuable infor-
mation.
You don’t need to know much about databases—we have included several
chapters that provide all of the basics necessary to create databases and make
sure they are operational. Keep in mind that we didn’t intend these chapters to
replace a good reference on MySQL, though.
We do expect that you are an experienced Java developer who is comfortable
with the language. This book explains a combination of Java delivery methods,
including applications, applets, beans, and EJBs; you may want to begin with
what you know best and expand from there.

The Technology Used


In this book, we use the latest Java Developments Kits (JDK) available from
Sun at the time of writing. The JDKs we used include J2SE 1.4.0 and J2EE 1.3.1.
The Java examples are used in a mixed environment, including Windows
2000/XP, Linux Mandrake, and Linux Slackware. For the most part, we devel-
oped the examples using simple text editors and compiled them using the Java
command-line compiler. However, all the examples should work just fine in an
IDE such as JBuilder.
xviii I NTRO D U CTI O N

Two different versions of MySQL are used throughout this book: 4.0.4 and
3.23.52. JDBC connectivity is handled using MySQL’s Connector/J driver, and
we cover both versions 2.0.14 and development 3.0.1.

Book Organization
The first four chapters of this book provide an overview of databases, JDBC,
and installation of the tools you will be using. The remainder of the book is an
in-depth guide to building database applications with MySQL, Connector/J,
JDBC, and Java.

Chapter 1: An Overview of MySQL


MySQL is one of the most popular open source database systems available
today, and it is used as the back-end data storage device for many personal
and corporate Web sites. Java is the most portable language in use today and
continues to be improved with each new release. In this chapter, we provide
a brief overview of each product and begin the discussion of how to interface
the two and thus allow Java applications to have access to a vast array of
information.

Chapter 2: JDBC and Connector/J


As shown in Chapter 1, JDBC facilitates the interface between Java and
MySQL. The JDBC specification defines the interfaces and classes necessary
for any Java application, applet, servlet, and so forth to make calls to an under-
lying database. Because the JDBC specification isn’t specific to any one data-
base system, manufacturers create JDBC drivers for their specific database. In
this chapter, we discuss the history of JDBC, how it started, and its progress
into a version 3.0 specification. We examine in depth the MySQL JDBC driver
called Connector/J, and look at its history as the MM.MySQL JDBC driver as
well as its future.

Chapter 3: Working with MySQL SQL


Before we delve into the concepts surrounding the interface between Java
and MySQL, this chapter provides a basic overview of databases and SQL.
Topics include basic concepts behind databases, simple database design,
database normalization, and data manipulation.

Chapter 4: Installing MySQL, Java, and Connector/J


MySQL and Java Developer’s Guide xix

All of the coding examples in this book are built using MySQL as the primary
database, Java as our coding language, and Connector/J, MySQL’s JDBC dri-
ver. Although the installation of these components isn’t overly difficult, this
chapter provides comprehensive instructions for obtaining all of the neces-
sary components and performing a step-by-step installation. We also provide
simple examples for testing the installation.

Chapter 5: Using JDBC with Java Applications and


Applets
This chapter is the first in a series on the use of Java to access a MySQL data-
base using JDBC. Some of the basic functionality discussed includes loading
the JDBC driver, connecting to a local or remote database, building JDBC
statements in preparation for queries, executing queries against the MySQL
database, working with ResultSets, and accessing MySQL-specific functional-
ity through JDBC.

Chapter 6: Achieving Advanced Connector/J Functionality


with Servlets
At this point, you’ve learned the basics, and it’s time to expand into the more
advanced topics. This chapter is designed to expand your understanding of
SQL, MySQL, and JDBC. The topics include updatable ResultSets, Prepared-
Statements, date/time types, BLOBs and CLOBs, and joins.

Chapter 7: MySQL Type Mapping


One of the fundamental issues associated with databases and programming
language is determining the correct mapping from one to the other. While
programming languages have a large variety of types, including simple ones
like integer, they also allow more complex ones, like classes. Databases, on
the other hand, are limited in their choices for the types of data that can be
stored. In the middle of this situation is the JDBC driver. This chapter dis-
cusses the types available on the MySQL database, how JDBC interprets
those types, and the resulting Java type produced by the mapping.

Chapter 8: Transactions and Table Locking with Connector/J


In a simple world, information is stored in a single table of a database. When
you have to update information or insert a new row, you can use a single
query. However, most modern databases store information across several dif-
ferent tables to increase the normalization of the tables. In this situation,
when you have to update information or insert new rows, you must write two
xx I NTRO D U CTI O N

queries instead of one. This chapter looks at inserting multiple pieces of infor-
mation into multiple tables, what problems can arise, and how transactions can
be used to solve these problems.

Chapter 9: Using Metadata


After a query is performed against a MySQL database, the information is
returned in a ResultSet object. This object includes all of the rows and columns
specific to the query performed. In many cases, additional information is
needed about the data, including the name of the columns in the result, the pre-
cision of the data in a float column, the maximum length of a column, and
maybe even information about the server from which the data was returned. In
this chapter, we discuss pulling metadata about both the database and a Result-
Set that contains information from a query.

Chapter 10: Connection Pooling with Connector/J


In many cases, a JDBC driver requires between 4 and 10 different communica-
tions with a database application before a connection can be established and
returned to the requesting application. If an application is constantly creating
connections, doing its business, and then closing the connection, the applica-
tion suffers in its potential performance. To overcome the connection perfor-
mance problem, you can use a connection pool. This chapter provides a
comprehensive introduction to connection pools, presents valuable statistics
for creating database connections, and demonstrates how to use the connec-
tion pooling mechanisms within JDBC.

Chapter 11: EJBs with MySQL


Enterprise JavaBeans (EJBs) provide the framework for building applications
that can handle the rigors of enterprise-level applications. In addition, EJBs can
be distributed across a network or a farm of servers. In this chapter, we cover
the basic EJB programming model, using DataSources and JNDI, and building
session beans to access MySQL. We also discuss container-managed persis-
tence and bean-managed entity beans.

Chapter 12: Building a General Interface for MySQL


All of the chapters to this point have featured relatively simple examples using
Java applications, applets, servlets, and JSP to illustrate the finer points of
accessing a MySQL database using Java and Connector/J. This chapter pulls it
MySQL and Java Developer’s Guide xxi

all together using a Certificate Authority application. Using JSP, servlets, and
EJB, the application shows how to create new accounts, request certificates,
and enable the verification of certificates. All of the information, including
the binary certificate, is stored in a MySQL database with multiple tables.

Chapter 13: Database


Administration
Once you have a good knowledge of the MySQL database system as well as
the fundamentals described in the previous chapters for accessing the data
from Java, you must learn some database administration basics. In this chap-
ter, we examine many of the functions within MySQL that benefit administra-
tors, such as granting/revoking permissions, providing security within the
server, and recovering from disasters.

Chapter 14: Performance and Tuning


Once the application is written and the information is safely sitting in a data-
base, the users get the final say on whether or not the application meets their
performance requirements. If the application isn’t running at an appropriate
level, you have a couple of options. First, you can profile the Java code to
determine where the application is spending the most time and then rework
the code associated with the problem areas. Second, you can tune the MySQL
server and create indexes for the database tables. In this chapter, we provide
the necessary information on performing these two options.

Appendix A: MySQL Development and Test Environments


We developed and tested all of the code in this book on several different test
architectures in order to provide a representative reference. This appendix
briefly describes those environments and lists the installed software. In addi-
tion, we offer some notes for reproducing the configuration.

Appendix B: Databases and Tables


In this appendix, we list all databases and tables used in the examples
throughout this book.

Appendix C: The JDBC API and Connector/J


This appendix is a comprehensive review of the entire JDBC API, with anno-
tations for Connector/J. Code snippets are provided to show at a quick glance
how to use the various interfaces, classes, and methods.
xxii I NTRO D U CTI O N

Appendix D: MySQL Functions and Operators


The list of MySQL functions and operators in this appendix will help you deter-
mine when the database should handle computations versus the application.
Each function and operator is described, and an example of its use is given.

Appendix E: Connector/J Late-Breaking Additions


The most current, up-to-date additions to Connector/J as it moves from gamma
to production version.
CHAPTER
1
An Overview of MySQL

I
n this chapter, we explain why you might choose to use a database system
with your software. We also provide an overview of the MySQL database
server and the Connector/J JDBC driver.
For many years, large corporations have enjoyed the ability to deploy relational
database management systems (RDBMSs) across their enterprise. Companies
have used these systems to collect vast amounts of data that serve as the “fuel”
for numerous applications that create useful business information.
Until recently, RDBMS technology has been out of reach for small businesses
and individuals. Widely used RDBMS systems such as Oracle and DB2 require
complex, expensive hardware. License fees for these systems are in the tens to
hundreds of thousands of dollars for each installation. Businesses must also
hire and retain staff with specialized skill sets to maintain and develop these
systems. Smaller enterprises have relied on systems like Microsoft Access and
FoxPro to maintain their corporate data.
Early on, during the explosive growth of the Internet, open source database
systems like mSQL, Postgres (now PostgreSQL), and MySQL became available
for use. Over a relatively short amount of time, the developers of these systems
have provided a large subset of the functionality provided by the expensive
commercial database systems. These open source database systems also run
on less-expensive commodity hardware, and have proven in many cases to be
easier to develop for and maintain than their commercial counterparts.

1
2 An Overview of MySQL

Finally, smaller businesses and individuals have access to the same powerful
level of software tools that large corporations have had access to for over a
decade.

Why Use an RDBMS?


Almost every piece of software that has been developed needs to persist or
store data. Once data has been persisted, it is natural to assume that this data
needs to be retrieved, changed, searched, and analyzed.
You have many options for data persistence in your software, from rolling your
own code, to creating libraries that access flat files, to using full-blown RDBMS
systems. Factors to consider when choosing a persistence strategy include
whether you need multiuser access, how you will manage storage require-
ments, whether you need transactional integrity, and whether the users of your
software need ad hoc query capability. RDBMSs offer all of this functionality.

Multiuser Access
Many programs use flat files to store data. Flat files are simple to create and
change. The files can be used by many tools, especially if they are in comma- or
tab-delimited formats. A large selection of built-in and third-party libraries is
available for dealing with flat files in Java. The java.util.Properties class
included with the Java Development Kit is one example.
Flat file systems can quickly become untenable when multiple users require
simultaneous access to the data. To prevent corrupting the data in your file, you
must lock the file during changes, and perhaps even during reads. While a file is
locked, it cannot be accessed by other users. When the file becomes larger and
the number of users increases, this leads to a large bottleneck because the file
remains locked most of the time—your users are forced to wait until they can
have exclusive access to the data.
RDBMSs avoid this situation by employing a number of locking strategies at
varying granularities. Rather than using a single lock, the database system can
lock an individual table, an individual page (a unit of storage in the database,
usually covering more than one row), or an individual row. This increases
throughput when multiple users are attempting to access your data, which is a
common requirement in Web-based or enterprise-wide applications.

Storage Transparency
If you use flat files in your software, you are also responsible for managing their
storage on disk. You have to figure out where and how to store the data, and
Random documents with unrelated
content Scribd suggests to you:
“Hush, Jack! Keep your temper,” whispered Alvar, in English.
“Señor, I am the grandson of Señor Don Guzman de la
Rosa, of Seville, well known as a friend to the government,
and this is my half-brother from England.”

“One of the De la Rosas, señor, is exactly what we know you


to be; but as for this extraordinary falsehood by which you
call yourself an Englishman—and the brother of this
gentleman—why, you make matters worse for yourselves
for attempting it.”

“Ask the guide,” said Alvar.

“Ah, doubtless; the fellow was known as having been


engaged in the late war. Come, señores, you may as well
accompany me in silence.”

“Will you send a message by the direct route to Ronda,


asking for our passports, and informing our friends of our
safety?” said Alvar.

No, informing their friends was the last thing wished for. In
the morning they would see.

“Do not resist, Jack,” said Alvar; “it is quite useless; we


must come.”

“Don’t you hear he is talking English to me?” said Jack, as a


last appeal, and, of course, a vain one.

“I am sure they haven’t got a magistrate’s warrant,” said


Jack, as his alpenstock was taken away from him, and,
closely guarded, he was made to precede Alvar down the
hill, in a state of offended dignity and incredulous
indignation. He was very angry, but not at all frightened; it
was incredible that any Spanish officials should hurt him.
Indeed, as he cooled down a little, the adventure might
have been a good joke, but for the certainty that Cherry
would be imagining them at the bottom of a precipice.

After walking for some way along a different road from the
one they had come by, they stopped at a little wayside
tavern, where they were given to understand that they
were to pass the night.

“But it’s impossible; they can’t keep us here,” cried Jack.


“Isn’t there a parish priest, or a magistrate, or a policeman,
or some one to appeal to?”

“No one who could help us,” answered Alvar. “I do not think
there is anything to be afraid of for ourselves; we can easily
prove that we are English when we get to some town; it is
of Cherry that I think—he will be so frightened.”

“You don’t think they’ll go and take him up?”

“Oh, no; I hope they will send to Ronda for our passports in
the morning. But, Jack, do not fly in a passion. We must be
very civil, and say we are quite willing to be detained in the
service of the government.”

“I’m hanged if I say anything of the sort,” muttered Jack,


whose prominent sensation was rage at the idea that he, an
Englishman, a gentleman, a man with an address, and a
card—though he had unluckily left it at home—should be
subjected to such an indignity, stopped in his proceedings
by a dozen trumpery Spaniards!

Alvar was not so full of a sense of the liberty of the subject;


he felt sure that he was mistaken for Manoel, and more
than suspected that the government might have been
justified in detaining his cousin. He did not, however, wish
to confide this to Jack, of whose prudence he was doubtful,
and knew that if the worst came to the worst, his
grandfather could get them out of the scrape.

There might be no danger, but it was very uncomfortable,


and provisions being scarce in the emergency, the captain—
who looked much more like a bandit than an officer—gave
his prisoners no supper but a bit of bread. Alvar was
Spaniard enough to endure the fasting, but Jack, after his
day of mountain climbing, was ready to eat his fingers off
with hunger; and as the hours wore on, began really to feel
sick, wretched, and low-spirited, and though he preserved
an unmoved demeanour, to wonder inwardly what his father
would say if he knew where he was, and to remember that
the Spaniards were a cruel people and invented the
Inquisition! And then he wondered if Gipsy was thinking of
him.

Moreover, it was very cold, and they were of course tired to


begin with, so that, when at length the morning dawned,
Alvar was startled to see how like Jack looked to Cheriton
after a bad night, and made such representations to the
captain that Englishmen could not bear cold and hunger,
that he obtained a fair share of bread and a couple of
onions—provisions which Jack enjoyed more than he would
have done had he guessed what Alvar had said to procure
them.

“I’m up to anything now,” he said. “If they would only let us


put a note in the post for Cherry, it would be rather a lark
after all.”

“I do not know where you will find a post-office,” said Alvar


disconsolately, as they were marched off in an opposite
direction to Ronda. “If Cherry only does not climb that
mountain to look for us!”
“I should like to set this country to rights a little,” said Jack.

“That,” said Alvar dryly, “is what many have tried to do, but
they have not succeeded.”

The prisoners were very well guarded, and though Alvar


made more than one attempt to converse with the captain,
he got scarcely any answer. Still, from the exceedingly
curious glances with which he regarded them, Alvar
suspected that he was not quite clear in his own mind as to
their identity. After a long day’s march they struck down on
a small Moorish-looking town, called Zahara, built beside a
wide, quick-rushing river.

And now Alvar’s hopes rose, as here resided an


acquaintance of his grandfather, a noted breeder of bulls,
who knew him well, and had once seen Cheriton at Seville.
Besides, the authorities of Zahara might be amenable to
reason.

However, they could get no hearing that night, and were


shut up in what Jack called the station-house, but which
was really a round Moorish tower with horseshoe arches.
Here Alvar obtained a piece of paper, and they concocted a
full description of themselves, their travelling companions,
and their destination, which Alvar signed with his full name,

“Alvaro Guzman Lester, of Westmoreland, England,” and


directed to El Señor Don Luis Pavieco, Zahara, and this he
desired might be given to the local authorities. He also tried
hard, but in vain, to get a note sent to Ronda.

They hoped that the early morning might produce Don Luis,
but they saw nothing of any one but the soldier who
brought them their food, which was still of the poorest.
Alvar’s patience began to give way at last; he walked up
and down the room.

“Oh, I am mad when I think of my brother!” he exclaimed.


“My poor Cheriton. What he will suffer!”

“Don’t you think they’ll let us out soon?” said Jack, who had
subsided into a sort of glum despair.

“Oh, they will wait—and delay—and linger. It drives me


mad!” he repeated vehemently, and throwing himself into a
seat he hid his face in his arms on the table.

“Well,” said Jack, “it’s dogged as does it. I wish I hadn’t


used up all my tobacco though.”

Early the next morning their door was opened at an unusual


hour, and they were summoned into a sort of hall, where
they found “el Capitano,” another officer in a respectable
uniform, and, to Alvar’s joy, Don Luis Pavieco himself.

The thing was ended with ludicrous ease. Don Luis bowed to
Alvar, and turning to the officer declared that Don Alvar
Lester was perfectly well known to him, and that the other
gentleman was certainly his half-brother and an
Englishman. The officer bowed also, smiled, hoped that they
had not been incommoded; it was a slight mistake.

“Mistake!” exclaimed Jack; “and pray, Alvar, what’s the


Spanish for apology—damages?”

Alvar turned a deaf ear, and bowed and smiled with equal
politeness.

“He had been sure that in due time the slight mistake would
be rectified. Were they now free to go?”
“Yes;” and Don Luis interposed, begging them to come and
get some breakfast with him while their horses could be got
ready. Their guide?—oh, he was still detained on suspicion.

“Well,” ejaculated Jack, “they are the coolest hands.


Incommoded! I should think we have been incommoded
indeed!”

In the meantime no hint of how matters had really gone


reached the anxious hearts at Ronda. The authorities had
scouted the idea of brigands, and had revealed the
existence of a dangerous ravine, some short distance from
the mountain path. Doubtless the darkness had overtaken
them, and they had been lost. The guides declared that
nothing was more unlikely, as it was hardly possible to
reach the ravine from the path, the rocks were so steep. A
search was however made by some of the most active, it
need not be said, in vain. Cheriton, afterwards, never could
bear a reference to those days and nights of suspense—
suspense lasting long enough to change the hope of good
tidings into the dread of evil tidings, till he feared rather
than longed for the sounds for which his whole being
seemed to watch.

Nothing could exceed Mr Stanforth’s kindness to him, and


he held up at first bravely, and submitted to his friend’s
care. On the third morning they resolved that Don Guzman
should be written to, and Cherry, who had been wandering
about in an access of restless misery, tried to begin the
letter; but he put down the pen, turning faint and dizzy, and
unable to frame a sentence.

“I cannot,” he said faintly. “I cannot see.”

“You must lie down, my dear boy; you have had no rest. I
will do it.”
“My father, too,” Cheriton said, with a painful effort at self-
control. “I think—there’s no chance. I must try to do it; but
—oh—Jack—Jack!”

He buried his face on his arms with a sob that seemed as if


it would tear him to pieces.

“You must not write yet to your father,” said Mr Stanforth. “I


do not give up hope. Courage, my boy!”

Suddenly a loud scream rang through the house, and an


outburst of voices, and one raised joyously,—

“My brother—my brother—are you here?—we are safe!” and


as Cherry started to his feet Alvar, followed by Jack, rushed
into the room, and clasped him in his arms.

“Safe! yes, the abominable, idiotic brutes of soldiers! But


we’re all right, Cherry. You mustn’t mind now.”

“Yes, we are here, and it is over.”

“Thank Heaven for His great mercy!” cried Mr Stanforth,


almost bursting into tears as he grasped Alvar’s hand.

“Bandits, bandits?” cried half-a-dozen voices.

But Cherry could not speak a word; he only put out his
hand and caught Jack’s, as if to feel sure of his presence
also.

“Mi querido,” said Alvar in his gentle, natural tones, “all the
terror is over—now you can rest. I think you had better go,
Jack. I will take care of him,” he added.

“Yes,” said Mr Stanforth; “this has been far too much.


Come, Jack—come and tell us all that has chanced.”
Chapter Thirty Four.
Jack on his Mettle.

“Lat me alone in chesing of my wyf,


That charge upon my bak I wol endure.”

Chaucer.

That same morning, when Jack and Alvar had ridden


hurriedly up to the hotel, looking eagerly to catch sight of
those who were so anxiously watching for them, their eyes
fell on Gipsy’s solitary figure, standing motionless, with eyes
turned towards the mountain, and hands dropped listlessly
before her. Jack’s heart gave a great bound, and at the
sound of the horses’ hoofs, she turned with a start and
scream of joy, and sprang towards them, while Jack,
jumping off, caught both her hands, crying,—

“Oh, don’t be frightened any more, we’re come!”

“Your brother!” exclaimed Gipsy, as she flew into the house;


but her cry of “Papa! papa!” was suddenly choked with such
an outburst of blinding, stifling tears and sobs, that she
paused perforce; and as they ran upstairs, Mariquita, the
pretty Spanish girl who waited on them, caught her hand
and kissed her fervently.

“Ah, señorita, dear señorita; thanks to the saints, they have


sent her lover back to her. Sweet señorita, now she will not
cry!”

A sudden access of self-consciousness seized on Gipsy; she


blushed to her fingertips, and only anxious to hide the tears
she could not check, she hurried away, round to the back of
the inn, into a sort of orchard, where grew peach and
nectarine trees, apples and pears already showing buds,
and where the ground was covered with jonquils and
crocuses, while beyond was the rocky precipice, and, far off,
the snowy peaks that still made Gipsy shudder. Unconscious
of the strain she had been enduring, she was terrified at the
violence of her own emotion, for Gipsy was not a girl who
was given to gusts of feeling. Probably the air and the
solitude were her best remedies, for she soon began to
recover herself, and sat up among the jonquils. Oh, how
thankful she was that the danger was over, and the bright,
kindly Cheriton spared from such a terrible sorrow! But was
it for Cheriton’s sake that these last two days had been like
a frightful dream, that her very existence seemed to have
been staked on news of the lost ones? No one—no one
could help such feelings. Miss Weston had cried about it,
and her father had never been able to touch a pencil. But
that foolish Mariquita! Here Gipsy sprang to her feet with a
start, for close at her side stood Jack. At sight of him,
strong and ruddy and safe, her feeling overpowered her
consciousness of it, and she said, earnestly,—

“Oh, I am so thankful you are safe! It was so dreadful!”

“And it was not dreadful at all in reality, only tiresome and


absurd,” said Jack.

“It was very dreadful here,” said Gipsy, in a low voice, with
fresh tears springing.

“Oh, if you felt so!” cried Jack ardently; “I wish it could


happen to me twenty times over!”

“Oh, never again!” she murmured; and then Jack, suddenly


and impetuously,—
“But I am glad it happened, for I found out up in that dirty
hole how I felt. There was never any one like you. I—I—
could you ever get to think of me? Oh, Gipsy, I mean it. I
love you!” cried the boy, his stern, thoughtful face radiant
with eagerness, as he seized her hand.

“Oh, no—you don’t!” stammered Gipsy, not knowing what


she said.

“I do!” cried Jack desperately. “I never was a fellow that did


not know his own mind. Of course I know I’m young yet;
but I only want to look forward. I shall work and get on,
and—and up there at school and at Oakby I never thought
there was any one like you. I disliked girls. But now—oh,
Gipsy, won’t you begin at the very beginning with me, and
let us live our lives together?”

Boy as he was, there was a strength of intention in Jack’s


earnest tones that carried conviction. Perhaps the mutual
attraction might have remained hidden for long, or even
have passed away, but for the sudden and intense
excitement that had brought it to the surface.

“Won’t you—won’t you?” reiterated Jack; and Gipsy said


“Yes.”

They stood in the glowing sunshine, and Jack felt a sort of


ecstasy of unknown bliss. He did not know how long was
the pause before Gipsy, starting, and as if finishing the
sentence, went on,—

“Yes—but I don’t know. What will they all say? Isn’t it wrong
when we are so young?”

“Wrong! as if a year or two made any difference to feelings


like mine!” cried Jack. “If I were twenty-five, if I were thirty,
I couldn’t love you better!”
“Yes—but—” said Gipsy, in her quick, practical way. “You are
young, and—and—papa—If he says—”

“Of course I shall tell him,” said Jack. “I am not going to


steal you. If you will wait, I’ll work and show your father
that I am a man. For I love you!”

“I’ll wait!” said Gipsy softly; and then voices sounded near,
and she started away from him, while Jack—but Jack could
never recollect exactly what he did during the next ten
minutes, till the thought of how he was to tell his story
sobered him. Practical life had not hitherto occupied much
of Jack’s mind; he had had no distinct intentions beyond
taking honours, and if possible a fellowship, till he had been
seized upon by this sudden passion, which in most lads
would probably have been a passing fancy, but in so earnest
and serious a nature took at once a real and practical
shape. But when Jack thought of facing Mr Stanforth, and
still worse his own father, with his wishes and his hopes, a
fearful embarrassment seized on him. No, he must first
make his cause good with the only person who was likely to
be listened to—he must find Cherry. However, the first
person he met was Mr Stanforth, who innocently asked him
if he knew where his daughter was. Jack blushed and
stared, answering incoherently,—

“I was only looking for Cherry.”

“There he is. I heard him asking for you. Perhaps Gipsy is in


the orchard.” Jack felt very foolish and cowardly, but for his
very life he could not begin to speak, and he turned towards
the bench where Cherry sat in the sun, smoking his pipe
comfortably, and conscious of little but a sense of utter rest
and relief.
“Well, Jack, I haven’t heard your story yet,” he said, as Jack
came and sat down beside him. “I don’t think you have
grown thin, though Alvar says they nearly starved you to
death.”

“Where is Alvar?” asked Jack.

“I got him to go to the mayor, intendant, whatever the


official is called here, and see if anything could be done for
poor Pedro. His mother was here just now in an agony.
Jack, I think the ‘evils of government’ might receive some
illustrations.”

“Cheriton,” said Jack, with unusual solemnity, “I’ve got to


ask your advice—that is, your opinion—that is, to tell you
something.”

“Don’t you think I should look at it from a ludicrous point of


view?” said Cherry, whose spirits were ready for a reaction
into nonsense.

“I don’t know,” said Jack; “but it is very serious. I have


made up my mind, Cherry, that I mean to marry Miss
Stanforth, and I shall direct all my efforts in life to
accomplish this end. I know that I am younger than is usual
on these occasions; but such things are not a question of
time. Cherry, do help me; they’ll all listen to you.”

Cheriton sat with his pipe in his hand, so utterly astonished,


that he allowed Jack’s sentences to come to a natural
conclusion. Then he exclaimed,—

“Jack! You! Oh, impossible!”

“I don’t see why you should think it impossible. Anyhow, it’s


true!”
“But it is so sudden. Jack, my dear boy, you’re slightly
carried off your head just now. Don’t say a word about it—
while we’re all together at least; it wouldn’t be fair.”

“But I have,” answered Jack, “and—and—” in a different


tone, “Cherry, I don’t know how to believe it myself, but she
—it is too wonderful—she will.”

Cherry did not answer. He put his hand on Jack’s with a


sudden, quick movement.

“I suppose you think I ought to have waited till I had a


better right to ask her,” said Jack presently.

A look of acute pain passed over Cheriton’s face. He said


doubtfully, “Are you quite sure?”

“Sure? Sure of what?”

“Of your own mind and hers?”

“Did I ever not know my own mind? I’m not a fool!” said
Jack angrily. “And, if you could have seen just the way she
looked, Cherry, you wouldn’t have any doubts.”

“I am afraid,” said Cherry very gently, and after a pause,


“that you have been very hasty. I don’t think that father, or
Mr Stanforth either, would listen to you now.”

“I want you to ask them,” said Jack insinuatingly. “Father


would do anything for you now; and, besides, we are young
enough to wait, and I’ve got the world before me, and I
mean to keep straight and get on. Why should Mr Stanforth
object? I feel as if I could do anything. You don’t think it
would make me idle? No, I shall work twice as hard as I
should without it.”
“Yes,” said Cherry quietly; “no doubt.” Something in his tone
brought recent facts to Jack’s remembrance, as was proved
by his sudden silence. Cherry looked round at him and
smiled.

“You know, Jack, I wasn’t prepared to find the schoolboy


stage passed into the lover’s. I’ll speak to Mr Stanforth, if
that is what you want, and even if things don’t fit in at
once, if you feel as you say, you won’t be much to be pitied
with such an aim before you!”

“I’m not at all ashamed of telling my own story,” said Jack,


“but—”

“But there is Mr Stanforth coming out of the house, so if


you mean to run away you had better make haste about it.”

Jack rose, but he paused a moment, and as Mr Stanforth


came towards them, said bluntly,—

“Mr Stanforth, I want Cheriton to tell you about it first;”


then deliberately walked away.

Poor Mr Stanforth, who had little expected such an ending


to his tour with his favourite little daughter, was feeling
himself in a worse scrape than the lovers, and though he
had romance enough to sympathise with them, was
disposed to be angry with Jack for his inconsiderate haste,
and to feel that “What will your mother say?” was a more
uncomfortable question to himself than to his daughter.

Cheriton, on his side, would have been very glad of a few


minutes for reflection, but Mr Stanforth began at once,—

“I see I have not brought news to you.”


“No,” said Cherry. “Jack has been talking to me; I had no
idea of such a thing. But, Mr Stanforth, there is no doubt
that Jack is thoroughly in earnest,” as a half smile twinkled
on the artist’s perplexed countenance.

“In earnest, yes; but what business has he to be in earnest?


What would your father say to such a proceeding? What can
he say at your brother’s age, and of people of whom he
knows nothing, and of a connexion of which, knowing
nothing, he probably would not approve?”

Cheriton blushed, knowing that this last assertion contained


much truth.

“But he does know,” he said, “of all your kindness, and he


will know more—and—and when he knows you, he could
not think—”

“Excuse me, my dear fellow, but he will think. He will think I


have thrown my daughter in the way of his sons—for which
I have only my own imprudence, I suppose, to thank. And
he would no doubt dislike a connexion the advantages of
which, whatever they may be, are not enumerated in
Burke’s ‘Landed Gentry.’”

Mr Stanforth smiled, though he spoke with a certain spirited


dignity, and Cheriton could not contradict him; for though
Mr Stanforth had not risen out of any romantic obscurity, he
certainly owed his present position to his own genius and
high personal character. He had himself married well, and
all would depend on the way in which it was put to a man
like Mr Lester, slow to realise unfamiliar facts. Cheriton
could not take the liberty of saying that he thought such an
objection would be groundless, or at least easily overcome;
but he was afraid that his silence might be misconstrued,
and said,—“But on your side, Mr Stanforth, would you think
it wrong to give Jack a little hope? I think he has every
prospect of success in life. And he is a very good fellow.
Sudden as this is, I feel sure that he will stick to it.”

“As to that,” said Mr Stanforth, “I like Jack very well, and for
my part I think young people are all the better for having to
fight their way; but whatever may take place in the future I
can allow no intercourse till your father’s consent is
obtained. That will give a chance of testing their feelings on
both sides. Gipsy is a mere child, she may not understand
herself.”

“I think,” said Cheriton, “that if Jack writes to my father


now, or speaks to him when he gets home, that no one will
attend to him. But if it could wait till we all go back, I could
explain the circumstances so much better. It is always
difficult to take in what passes at a distance.”

“Well,” said Mr Stanforth, “all I have to say is that when


Jack applies to me, with his father’s consent, I will hear
what he has to say, not before. Come, Cheriton,” he added,
“you know there is no other way of acting. This foolish boy
has broken up our pleasant party, and upset all our plans.”

“Perhaps I ought to have made more apologies for him,”


said Cherry, with a smile. “But I want things to go well with
Jack. It would be so bad for him to have a disappointment
of that kind just as he is making his start in life.”

Mr Stanforth noticed the unconscious emphasis, “I want


things to go well with Jack,” and said kindly, “Jack couldn’t
have a better special pleader, and if he has as much stuff in
him as I think, a few obstacles won’t hurt him.”

“Oh, Jack has plenty of good strong stuff in him, mental,


moral—and physical, too,” added Cherry hurriedly.
Mr Stanforth was touched by the allusion, which was
evidently intended to combat a possible latent objection on
his part.

“Jack is excellent—but inconvenient,” he said, thinking it


better not to make the subject too serious. “The thing is
what to do next.” As he spoke, Jack himself came up to
them, and Mr Stanforth prevented his first words with, “My
dear fellow, I have said my say to your brother, and I don’t
mean to listen to yours just yet.”

“I believe, sir,” said Jack, “that I—I have not observed


sufficient formalities. I shall go straight home to my father,
and I hope to obtain his full consent. But it is due to me to
let me say that my mind is, and always will be, quite
unalterable. And I’m not sorry I spoke, sir—I can’t be!”

“No,” said Mr Stanforth; “but I must desire that you make


no further attempt at present.”

“I hope, Mr Stanforth, that you don’t imagine I would


attempt anything underhand!” cried Jack impetuously.

“I shall have every confidence in you,” said Mr Stanforth


gravely; “but remember, I cannot regard you as pledged to
my daughter by anything that has passed to-day.” Jack
made no answer, but he closed his lips with an expression
of determination.

When Alvar came back, having succeeded in instituting an


inquiry into the merits of Pedro’s character, there was a
discussion of plans, which ended in the three brothers
agreeing to go by the shortest route to Seville, whence Jack
could at once start for England; while the Stanforths
followed them by a longer and more picturesque road, and
after picking up their own property, would also go home via
Madrid some week or two later. Alvar was not nearly so
much astonished as the others, nor so much concerned.

“It was natural,” he said, “since Jack’s heart was not


preoccupied, and would doubtless pass away with absence.”

Jack was so excessively indignant that he did not


condescend to a reply, only asking Cherry if he was too
tired to start at once.

This proposal, however, was negatived by Mr Stanforth, who


remarked that he did not want to hear of any more
adventures in the dusk; and it was agreed that both parties
should start early on the following morning. In the
meantime the only rational thing was to behave as usual.
Jack was, however, speechless and surly with
embarrassment, and stuck to Cheriton as if he was afraid to
lose sight of him; while Gipsy bore herself with a
transparent affectation of unconsciousness, and, though she
blushed at every look, coined little remarks at intervals.
Miss Weston kindly professed to be seized with a desire to
inspect the Dominican Convent, and carried her and Alvar
off for that purpose; while Jack held by Cherry, who was
glad to rest, though this startling incident had one good
effect, in driving away all the haunting memories of the late
alarm.

The next morning all were up with the sun, Gipsy busily
dispensing the chocolate and pressing it on Cheriton as he
sat at the table. Suddenly she turned, and, with a very
pretty gesture, half confident, half shy, she held up a cup to
Jack, who stood behind.

“Won’t you have some?” she said, with a hint of her own
mischief in her eyes and voice. Jack seized the cup, and—
upset it over the deft, quick hands that tendered it to him.
“Oh, I have burnt you!” he exclaimed, in so tragic a voice
that all present burst out laughing.

“No,” said Gipsy, “early morning chocolate is not


dangerously hot; but you have spoiled my cuffs, and spilled
it, and I don’t think there’s any more of it.”

“Jack’s first attention!” said Cherry, under his breath; but he


jumped up and followed Alvar, who had gone to see about
the mount provided for them. Miss Weston was tying
various little bags on to her saddle.

“I say, Mr Stanforth,” called Cherry, “there’s such a


picturesque mule here; do come and see it.”

He looked up with eyes full of mischievous entreaty as Mr


Stanforth obeyed his call. “Well,” said the latter with a
smile, “I may ask you to come and see me at Kensington,
for I must get the picture finished.”

“That was a much prettier picture, just now,” said Cheriton;


“and I’m sure Jack would be happy to sit for it any time.”

When Gipsy, long afterwards, was pressed on the subject of


that little parting interview, she declared that Jack had done
nothing but say that he wouldn’t make love to her on any
account; but however that might be, she soon came
running out, rosy and bashful; while Cheriton put her on her
mule and gave her a friendly hand-squeeze and a look of all
possible encouragement. Mr Stanforth went into the house
and called Jack to bid him a kind farewell. After the party
had set off, Gipsy looked back and saw the crowd of mule
drivers and peasants, the host and hostess, with Mariquita
kissing her hands, and the three brothers standing together
in the morning sunshine, waving their farewells. As they
passed out of sight, her father touched her hand and made
her ride up close to his side.
“My little girl,” he said, “this is a serious thing that has come
to you; I do not know how it may end for you. I am sure
that it will bring you anxiety and delay. Be honest with
yourself, and do not exaggerate the romance and
excitement of these last few days into a feeling which may
demand from you much sacrifice.”

Gipsy had never heard her father speak in this tone before
—she was awed and silenced.

“Be honest,” repeated her father, “for I think it is a very


honest heart that you have won.”

“Papa,” said Gipsy, “I am honest, and I think I know what


you mean. But I don’t mind waiting if I know he is waiting
too. He said ‘begin at the beginning’ with him.”

“Well,” said Mr Stanforth with a sigh, “Che sará sará;” but


with a sudden turn, “He is young, too, you know, and many
things may happen to change his views.”

“I cannot help it now, papa,” said Gipsy, who felt that those
days and nights of terror had developed her feelings more
than weeks of common life. She gave her father’s hand a
little squeeze, and looked up in his face with the tears on
her black eyelashes. She meant to say, “I love you all the
better because of this new love which has made everything
deeper and warmer for me,” but all she managed to say was
—“There! There are all the things tumbling out of your
knapsack! I’m not going to have that happen again even if—
if—whatever should take place in the future.”

“I hope, my dear, that nothing more will happen, at least till


we are at home again,” said Mr Stanforth meekly; but Gipsy
put the things into the knapsack, and after a little silence
they fell into a conversation on the scenery as naturally as
possible.
Chapter Thirty Five.
A Summons.

“Once from high Heaven


Is a father given.
Once—and, oh, never again!”

After Jack returned home, with the understanding that the


disclosure of his holiday occupation should await his
brother’s return, and after the Stanforths had also left
Seville, Alvar and Cheriton spent several weeks there
without any adventures to disturb their tranquillity. Alvar
was a good deal with his grandfather, whose health was not
at this time good, but who had evinced great curiosity as to
the details of their detention on the mountains. He used
also to go to the different clubs and meet acquaintances,
where they talked politics and scandal, and played at cards,
dominoes, and billiards. It was an aimless existence, and
Cheriton sometimes fancied that Alvar grew restless under
it, and would not be sorry to return to England. This,
however, might have been owing to Cheriton’s own decided
dislike to the young Sevillanos, who struck him as almost
justifying his grandmother’s preconceived theory of Alvar’s
probable behaviour.

“Ah, they do not suit you, that is not what you like,” Alvar
said cheerfully; but he never said, “It is not good, this sort
of life does not make a nation great or virtuous.”

Manoel was of another type, and perhaps a more


respectable one; but they saw very little of him. Cheriton
liked the ladies, who were kind, and possessed many
domestic virtues; and at Don Guzman’s country place there
was something exceedingly pleasant in the cheerfulness and
gaiety of the peasants. He would have liked to have found
out something of the working of the Church, of the views of
the clergy, and how far they differed, not only from those of
an Anglican, but of an intelligent Roman priest in more
civilised countries, but on these subjects no one would talk
to him. He heard mutterings of hatred towards the priests
in some quarters, and a good deal of chatter about
processions and ceremonies from the young ladies, but
nothing further. He did not want for occupation. He could
now read and speak Spanish easily; and although the Cid,
Ferdinand and Isabella, the Armada, and the Inquisition had
been about the only salient points in his mind previously, he
made a study of Spanish history, without much increase of
his admiration for the Spaniards. He was able, also, to do
much more sight-seeing than at first, and of the cathedral
he never tired, and never came to the end of its
innumerable chapels, each with some great picture, which
Mr Stanforth had taught him how to see; never ceased to
find something new in the mystery and solemnity of its
aisles with their glory of coloured lights.

These quiet weeks formed a sort of resting-place, during


which he was able to think both of the past and of the
future; he could dare now to look away from the immediate
present. Cheriton’s eyes were very clear, his moral sense
very keen, and he saw that he had been under a delusion,
that Ruth and he were as the poles asunder, that her
deliberate deception, her want of any sense of honour, had
marked a nature that never could have satisfied his. Love in
his case was no longer blind, but it was none the less
passionate, and, whatever else life might hold for him, the
memory of all his first, best hopes could never bring him
anything but pain. This pain had been as much as he could
bear, but others, he thought, had suffered as keenly, and
had led lives that were neither ignoble nor unhappy.
Because one great love had gone out of his life was nothing
else worthy or dear? “Nothing” had been the answer of his
first anguish, but Cheriton’s nature was too rich in love for
such an answer to stand. The help for which he had prayed
had been sent to him, and it came in the sense that home
faces were still dear—how dear his late alarm had taught
him—home duties still paramount, that he could be a good
son and brother and friend still. And he thought with a sort
of surprise of the many pleasant and not unhappy hours he
had passed of late; how much, after all, he had “enjoyed
himself.” He hardly knew that his quick intelligence was a
gift to be thankful for, or that his unselfish interest in others
brought its own reward. On another side of his nature, also,
he resisted the aimlessness of his lost hopes. The thought
of Ruth had sweetened his success at Oxford, but he would
not be such a coward as to give up all his objects in life, he
would make a name for himself still, and show her that she
had not brought him to utter shipwreck. This motive was
strong in Cheriton, though it ran alongside with much
higher ones.

One picture in the cathedral exercised a great fascination


over Cheriton’s mind. It hangs in the Capella del Consuelo,
over a side altar, dedicated to the Angel de la Guarda, and
is one of the many masterpieces of Murillo to be found in
Seville. It represents a tall, strong angel with wide-spread
wings, and grave, benevolent face, leading by the hand a
child—a subject which has been of course repeated in every
form of commonplace prettiness. But in this picture the
figure of the angel conveys a sense of heavenly might and
unearthly guardianship which no imitation or repetition
could give. It is called the “Guardian Angel;” but Cheriton
had been told by one of the priests that the name given to
it by the painter himself was “The Soul and the Church,”
which for some reason or other had been changed by the
monks of the Capuchin Convent, to whom the picture had
originally belonged. It was a thought and a carrying out of
the thought which, seen among such surroundings, was full
of suggestion, how and why that Divine Guidance seemed
here in great measure to have gone astray, how the great
angel’s finger had not always pointed upward, and yet how
utterly helpless and rudderless the nation was when it cast
off the Guide of its fathers. Then his thoughts turned to his
own life and to the Hand that held it, to the Guidance that
was sometimes so hard to recognise, so difficult to yield to,
and yet how the sense of a love and a wisdom above his
own, speaking to him, whether in the events of his own life,
the better impulses of his own heart, or in the visible forms
of religion, was the one light in the darkness.

“O’er moor and fen, o’er crag and torrent, till


The night is gone.”

As he murmured the words half aloud a hand touched his


shoulder. He looked up and saw Alvar standing beside him.

“Mi querido, I have been looking for you. Will you come
home? I want you,” he said.

“There is something the matter,” said Cheriton quickly, as he


looked at him. “What is it?”

“Ah, I must tell you!” said Alvar reluctantly. “It is bad news,
indeed. Sit down again—here—I have received this.” He
took a telegraph paper out of his pocket and put it into
Cherry’s hand.

“Mrs Lester to Alvar Lester.


“Your father has met with a dangerous accident. He
wishes to see you. Come home at once. He desires
Cheriton to run no risk.”
Cheriton looked up blankly for a moment, then started
to his feet, crushing up the paper in his hand.
“Quick,” he said, “we must go at once. When? By Madrid is
the shortest way.”

“Yes—I—” said Alvar; “but see what he says.”

“I must go,” said Cheriton. “Don’t waste any words about it.
I know he wants me. I’ll be careful enough, only make
haste.”

But he paused, and dropping on his knees on the altar step,


covered his face with his hands, rose, and silently led the
way out of the cathedral.

Alvar, with his usual tact, perceived at once that it would be


impossible to persuade him to stay behind, and did not fret
him by the attempt, though this hasty journey and the
return to Oakby in the first sharp winds of March were more
on his own mind than the thought of what news might meet
them at the journey’s end.

It was still early in the day, and they were able to start
within a few hours, only taking a few of their things with
them, amid a confusion of tears, sympathy, and regret; Don
Guzman evidently parting from Alvar with reluctance, and
bestowing a tremendous embrace on Cheriton in return for
his thanks for the kindness that had been shown to him.
Manoel, on the other hand, was evidently relieved at their
early departure.

Some days later, on a wild, blustering morning in the first


week of March, Jack Lester stood on the step of the front
door of Oakby. The trees were still bare, and scarcely a
primrose peeped through the dead leaves beneath them;
pale rays of sun were struggling with the quick driven
clouds, the noisy caw of the rooks mingled with the rustle of
the leafless branches. Jack was pale and heavy-eyed. He
looked across the wide, wild landscape as if its very
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like