Thursday, January 29, 2009

How To Insert Data Into Table

With our database and table defined, we need to add it with sample data.Here’s the data that we would like to insert into the table:



id username password


1000001 jhon jhn

1000002 Michael Mic



We can place the data in the database table by using the INSERT command. The format of the MySQL INSERT command is:



INSERT INTO <table> VALUES(<columnValue>,<columnValue>,..)



We have to issue three INSERT commands to get all of the information into the database. Here’s the output from one INSERT:



mysql> INSERT INTO person VALUES(1000001, ’jhon’, ’jhn’);

Query OK, 1 row affected (0.00 sec)

Introducing

Let’s examine the INSERT command a little more closely. First consider the order of the data. The order must match the columns defined in the table as shown by the DESCRIBE command. The second important factor is the use of single quotes to indicate a value is a string and should be treated as such by MySQL. If you didn’t want to insert a password into a row, you could use a NULL value. For example:



mysql> INSERT INTO person VALUES(1000002, ’Michael’, NULL);

Query OK, 1 row affected (0.00 sec)



In this example, the NULL value is placed directly into the database in place of a string value.