CREATE TABLE phoneList id INT PRIMARY KEY, firstName VARCHAR15, lastName VARCHAR 15, email VARCHAR20, phone VARCHAR15 ; You can think of fields as being much like variables, but while PH
Trang 1CREATE TABLE phoneList (
id INT PRIMARY KEY,
firstName VARCHAR(15),
lastName VARCHAR (15),
email VARCHAR(20),
phone VARCHAR(15)
);
You can think of fields as being much like variables, but while PHP is easy-going about what type of data is in a variable, SQL is very picky about the type of data
in fields In order to create an efficient database, MySQL needs to know exactly how many bytes of memory to set aside for every single field in the database It does this primarily by requiring the database designer to specify the type and size of every field in each table Table 9.2 lists a few of the primary data types sup-ported by MySQL
While the data types listed in Table 9.2 are by far the most commonly used, MySQL supports many others Look in the online Help that ships with MySQL if you need a more specific data type Other databases have a very similar list of data types.
You might notice that it is unnecessary to specify the length of numeric types (although you can determine a maximum size for numeric types as well as the number of digits you want stored in float and double fields) The storage require-ments for numeric fields are based on the field type itself
T R I C K
308
l u
INT Standard integer +/– 2 billion (roughly)
BIGINT Big integer +/– 9 x 10 ^18 th
FLOAT Floating-point decimal number 38 digits
DOUBLE Double-precision floating-point 308 digits
CHAR(n) Text with n digits; if actual value is less than n, field is padded with trailing
spaces VARCHAR(n) Text with n digits; trailing spaces are automatically culled
DATE Date in YYYY-MM-DD format
TIME Time in HH:MM:SS format
YEAR Year in YYYY format
T A B L E 9 2 C O M M O N D A T A T Y P E S I N M Y S Q L
Trang 2Working with String Data in MySQL
Text values are usually stored in VARCHAR fields These fields must include the
number of characters allocated for the field Both CHARand VARCHARfields have
fixed lengths The primary difference between them is what happens when the
field contains a value shorter than the specified length
Assume you declared a CHARfield to have a length of 10with the following SQL
segment:
firstName VARCHAR(10);
Later you store the value ‘Andy’ into the field The field actually contains
‘Andy ’ (That is, Andyfollowed by six spaces.) CHARfields pad any remaining
characters with spaces The VARCHAR field type removes any padded spaces The
VARCHARfield type is the one you use most often to store string data
Finishing the CREATE TABLE Statement
Once you understand field data types, the CREATE TABLE syntax makes a lot of
sense Only a few more details to understand:
• Use a pair of parentheses to indicate the field list once you specify CREATE
TABLE
309
i n
D ETERMINING THE L ENGTH OF A VARCHAR F IELD
Data design is both a science and an art Determining the appropriate length for
your text fields is one of the oldest problems in data.
If you don’t allocate enough room for your text data, you can cause a lot of
prob-lems for your users I once taught a course called CLT SD WEB PRG because the
database that held the course names didn’t have enough room for the actual
course name (Client-Side Web Programming) My students renamed it the Buy
a Vowel course.
However, you can’t make every text field a thousand characters long, either,
because it would waste system resources If you have a field that will usually
con-tain only five characters and you allocate one hundred characters, the drive still
requires room for the extra 95 characters If your database has thousands of
entries, this can be a substantial cost in drive space In a distributed environment,
you have to wait for those unnecessary spaces to come across limited bandwidth
It takes experimentation and practice to determine the appropriate width for
your string fields Test your application with real users so you can be sure
you’ve made the right decision.
Trang 3• Name each field and follow it with its type (and length, if it’s a CHARor VARCHAR)
• Separate the fields with commas
• Put each field on its own line and indent the field definitions You don’t have to, but I prefer to, because these practices make the code much easier
to read and debug
Creating a Primary Key
You might be curious about the very first field in the phone list database Just to refresh your memory, the line that defines that field looks like this:
id INT PRIMARY KEY,
Most database tables have some sort of field that holds a numeric value This spe-cial field is called the primary key
You can enter the code presented so far directly into the MySQL program You can see the code and its results in Figure 9.6
Using the DESCRIBE Command to Check a Table’s Structure
Checking the structure of a table can be helpful, especially if somebody else cre-ated it or you don’t remember exactly its field types or sizes The DESCRIBE com-mand lets you view a table structure
310
l u
I N THE R EAL W ORLD
A simple database could theoretically go without a primary key, but such fields are so important to more sophisticated databases that you might as well start putting them in It’s traditional to put a primary key in every table
In chapter 11, “Data Normalization,” you learn more about the relational data model In that discussion you learn how keys build powerful databases and more about creating proper primary keys In fact, the adventure program you’ve already seen heavily relies on a key field even though there’s only one table in the database.
Trang 4Inserting Values
Once you’ve created a table, you can begin adding data to it The INSERT
com-mand is the primary tool for adding records
INSERT INTO phoneList
VALUES (
0, ‘Andy’, ‘Harris’, ‘aharris@cs.iupui.edu’, ‘123-4567’
);
The INSERTstatement allows you to add a record into a database The values must
be listed in exactly the same order the fields were defined Each value is
sepa-rated by a comma, and all VARCHARand CHARvalues must be enclosed in single
quo-tation marks
If you have a large amount of data to load, you can use the LOAD DATAcommand
This command accepts a tab-delimited text file with one row per record and
fields separated by tabs It then loads that entire file into the database This is
often the fastest way to load a database with test data The following line loads
data from a file called addresses.txtinto the phoneListtable:
LOAD DATA LOCAL INFILE “addresses.txt” INTO TABLE phoneList;
Figure 9.7 shows the MySQL tool after I have added one record to the table
311
i n
FIGURE 9.6
This is the MySQL
command-line tool
after I created the
phoneList table.
Trang 5Selecting Results
Of course, you want to see the results of all your table-building activities If you want to see the data in a table, you can use the SELECTcommand This is perhaps the most powerful command in SQL, but its basic use is quite simple Use this command to see all of the data in the phoneListtable:
SELECT * FROM phoneList
This command grabs all fields of all records of the phoneListdatabase and dis-plays them in table format
Figure 9.8 shows what happens after I add a SELECTstatement to get the results
312
l u
As you are building a database, populate the database with test values Don’t use actual data at this point, because your database will not work correctly until you’ve messed with it for some time However, your test values should be reflective of the kinds of data your database will house This helps you spot cer-tain problems like fields that are too small or missing.
FIGURE 9.7
MySQL tells you the
operation
succeeded, but you
don’t get a lot more
information.