By: Sathya Narayana Printer Friendly Format
To insert data, follow these steps:
For example, to insert data for a book titled Lord of the Things, you'd enter the following:
mysql> INSERT INTO book (title, price) VALUES -> ('Lord of the Things', 9.99);
Note that you specify the fields (or columns) that are to be populated by this command after the table name and then list the values for these fields in the same order. All fields and values are separated by commas, and strings are delimited by single or double quotes.
To check that the data has been placed in your table correctly, run the following command:
mysql> SELECT id, title, price, status FROM book;
This should display something similar to this:
+----+--------------------+-------+--------+ | id | title | price | status | +----+--------------------+-------+--------+ | 1 | Lord of the Things | 9.99 | P | +----+--------------------+-------+--------+
Notice that as an auto-increment field, the id column has automatically been set to 1 for this first record. Also, the status column has the value P because this is the default you set earlier.
Now you'll add details for another couple of books. You can insert more than one record at a time by giving more than one set of values, each separated by commas. Run the following SQL command:
mysql> INSERT INTO book (title, price) VALUES -> ('Mr Bunny\'s Guide to JDO', 14.99), -> ('Parachuting for You and Your Kangaroo', 19.99);
Notice that the first of these two books demonstrates a title string that contains a single quote character. You can't use a quote character as is because MySQL would assume that you're finishing the string at that point and return an error when it came to the rest of our string.
To get around this, you have to use escape characters, where you precede the quote with a backslash character (\) to make \'. Astute readers might be wondering what you'd do if your book title contained the sequence \'. You'd then need to use the \\ escape character for the backslash, followed by the one for the single quote, to make \\\' altogether. Alternatively, you could simply change your string to use double quotes at either end because as long as the type of quotes (single or double) surrounding the string is different from those inside it, there won't be any confusion.
Check that all three books have been added as expected by running the same SELECT statement you used in step 2. Note how the id field is incremented for each new record.
Most Viewed Articles (in MySQL )
Latest Articles (in MySQL)
Comment on this tutorial
- Data Science
- Cloud Computing
- Java Beans
- Mac OS X
- Office 365
- Tech Reviews