The SQL command used to create a new table in a database typically looks like this:
CREATE TABLE table-name (field-name-1 field-type-1 modifiers,
field-name-2 field-type-2 modifiers, ... , field-name-n
field-type-n modifiers)
The table name cannot contain spaces, slashes, or periods; other than this, any
character is fair game. Each table (and the data it contains) is stored as a set of three
files in your MySQL data directory.
Here’s a sample command to create the members table in the example you saw a
couple sections back:
mysql> CREATE TABLE members (member_id int(11) NOT NULL auto_increment,
fname varchar(50) NOT NULL, lname varchar(50) NOT NULL, tel varchar(15),
email varchar(50) NOT NULL, PRIMARY KEY (member_id));
Once you’ve created a table, it’s time to begin entering data into it, and the SQL command
to accomplish this is the INSERT command. The syntax of the INSERT command is as
follows:
INSERT into table-name (field-name-1, field-name2, field-name-n)
VALUES(value-1, value-2, value-n)
Here’s an example:
mysql> INSERT INTO members (member_id, fname, lname, tel, email)
VALUES (NULL, 'John', 'Doe', '1234567', 'jdoe@somewhere.com');
You could also use the abbreviated form of the INSERT statement, in which field
names are left unspecified:
mysql> INSERT INTO members VALUES (NULL, 'John', 'Doe', '1234567',
'jdoe@somewhere.com');
Here’s the flip side: by specifying field names in the INSERT statement, I have
the flexibility of inserting values in any order I please. Because of this, the following
statements are equivalent:
mysql> INSERT INTO members (member_id, fname, lname, tel, email)
VALUES (NULL, 'John', 'Doe', '1234567', 'jdoe@somewhere.com');
and
mysql> INSERT INTO members (fname, lname, email, tel, member_id)
VALUES ('John', 'Doe', 'jdoe@somewhere.com', '1234567', NULL);
Fields that are not specified will automatically be set to their default values.
0 comments:
Post a Comment