INSERT a row record into a MySQL DATA table)

Source: Internet
Author: User
Tags how to use sql

Abstract: loading data for a database is one of the important responsibilities of the Administrator. It is precisely because of the importance that MySQL provides a wide range of methods. The INSERT and LOAD statements are mainly used.

INSERT new data using the INSERT statement

Syntax: INSERT [INTO] tbl_name [(col_name,...)] VALUES (pression ,...),...
INSERT [INTO] tbl_name SET col_name = expression ,...

Let's start to use the INSERT statement to add records. This is an SQL statement. You need to specify the table for which you want to INSERT data rows or the table that puts values by row. The INSERT statement has several forms:

You can specify the values of all columns:

For example:

Shell> mysql-u root-p
Mysql> use mytest;
Mysql> insert into worker values ("tom", "tom@yahoo.com ");


The word "INTO" is optional since MySQL 3.22.5. (This is also true for other forms of INSERT statements .) The VALUES table must contain the VALUES of each column in the table and are given in the order of column storage in the table. (Generally, this is the sequence in which columns are defined when a table is created. If not, use DESCRIBE tbl_name to view the order .)

Multiple value tables can provide multiple rows of data at a time.

Mysql> insert into worker values ('Tom ', 'Tom @ yahoo.com'), ('Paul ', 'Paul @ yahoo.com ');

The INSERT... VALUES format with multiple value tables is supported in MySQL 3.22.5 or later versions.

You can give the column to be assigned a value and then list the values. This is useful for creating records that require initial settings for only a few columns.

For example:

Mysql> insert into worker (name) values ('Tom ');

Since MySQL 3.22.5, this form of INSERT also allows multiple value tables:

Mysql> insert into worker (name) values ('Tom '), ('Paul ');

All columns without names in the column list will be given the default value.

Since MySQL 3.22. 10, columns and values can be given in the form of col_name = value.

For example:

Mysql> insert into worker set name = 'Tom ';

A default value is assigned to all rows not named in the SET clause.

INSERT statements in this form cannot INSERT multiple rows.

An expression can reference any column previously set in a value table. For example, you can:

Mysql> insert into tbl_name (col1, col2) VALUES (15, col1 * 2 );

But it cannot be like this:

Mysql> insert into tbl_name (col1, col2) VALUES (col2 * 2, 15 );

Use INSERT... SELECT statement insert selected rows from other tables

When we learn how to create a table in the previous section, we know that you can use select to directly create a table from other tables, or even copy data records at the same time. If you already have a table, you can also benefit from the cooperation of select statements.

Input data from other tables, for example:

Mysql> insert into tbl_name1 (col1, col2) select col3, col4 from tbl_name2;

You can also skip the column list of the target table if each column has data input.

Mysql> insert into tbl_name1 select col3, col4 from tbl_name2;

The insert into... SELECT statement meets the following conditions:

A query cannot contain an order by clause.

The target table of the INSERT statement cannot appear in the FROM clause in the SELECT query section, because this is forbidden in ansi SQL to allow the SELECT statement FROM the table you are inserting. (The problem is that SELECT may find records previously inserted during the same running period. When a sub-selection clause is used, the situation can be easily confused)

Use replace, replace... Insert select statement

The REPLACE function is exactly the same as the INSERT function. If an old record in the table has the same value for a new record with a unique index, the old record is deleted before the new record is inserted. In this case, the insert statement produces an error.

The REPLACE statement can also be used with the brown SELECT statement. Therefore, the content in the last two sections is suitable for REPALCE ..

Note that the REPLACE statement may change the original record, so be careful when using it.

Batch Data Input Using the LOAD statement

This chapter describes how to use SQL statements to insert data into a table. However, if you need to add many records to a table, it is inconvenient to input data using SQL statements. Fortunately, MySQL provides some methods for batch data entry, making it easy to add data to a table. This section and the next section describe these methods. This section describes the SQL language-level solutions.

1. Basic syntax

Syntax: load data [LOCAL] INFILE file_name.txt [REPLACE | IGNORE] into table tbl_name the load data infile statement reads a TABLE at a high speed from a text file. If you specify the LOCAL keyword, read the file from the client host. If LOCAL is not specified, the file must be on the server. (LOCAL is available in MySQL 3.22.6 or a later version .)

For security reasons, when reading text files on the server, the files must be in the database directory or can be read by everyone. In addition, to use load data infile for files on the server, you must have the file permission on the server host. See Chapter 7 database security.

The REPLACE and IGNORE keywords control repeated processing of existing unique key records. If you specify REPLACE, the new row replaces the existing row with the same unique key value. If you specify IGNORE, skip the input of duplicate rows of existing rows with a unique key. If you do not specify any option, an error occurs when the duplicate key is found and the remaining part of the text file is ignored.

If you use the LOCAL keyword to load data from a LOCAL file, the server cannot stop file transmission during the operation. Therefore, the default behavior is as if IGNORE was specified.

2. File Search principles

When searching for files on the server host, the server uses the following rules:

If an absolute path name is provided, the server uses this path name.

If a relative path name of one or more front parts is given, the server searches for files in the data directory relative to the server.

If a file name without a front-end component is provided, the server searches for a file in the database directory of the current database.

Note that these rules mean that a file such as "./myfile.txt" is read from the data directory of the server and written as "Prepare myfile.txt". A file is read from the database directory of the current database. Note which of the following statements read the db1 file from the database directory instead of db2:

Mysql> USE db1;
Mysql> load data infile "./data.txt" into table db2.my _ table;


3. Syntax of FIELDS and LINES clauses

If you specify a FIELDS clause, each of its clauses (terminated by, [OPTIONALLY] enclosed by and escaped by) is optional, except that you must specify at least one of them.

If you do not specify a FIELDS clause, the default value is the same as if you write this statement:

Fields terminated by enclosed by escaped \

If you do not specify a LINES clause, the default value is the same as if you write this statement:

LINES TERMINATED

In other words, when the default value causes reading input, load data infile performs as follows:

Search for line boundary at line breaks

Split the row into fields at the location Operator

Do not expect fields to be enclosed by any quotation marks

The delimiters, linefeeds, or "\" starting with "" are part of the literal characters of the field value.

Load data infile can be used to read files obtained from external sources. For example, a file in dBASE format will have fields separated by commas and enclosed by double quotation marks. If the row in the file is terminated by a line break, the command shown below describes the fields and row processing options you will use to load the file:

Mysql> load data infile data.txt into table tbl_name

Fields terminated by, enclosed"

Lines terminated;


Any field or line processing option can specify an empty string (). If it is not null, the value of FIELDS [OPTIONALLY] enclosed by and fields escaped by must be a single character. Fields terminated by and lines terminated by can be more than one character. For example, write a row terminated by a carriage return or read a file containing such a row and specify a lines terminated by clause.

FIELDS [OPTIONALLY] enclosed by control field surrounded BY characters. For output (SELECT... into outfile), if OPTIONALLY is omitted, all fields are surrounded by enclosed by characters. An example of such output (using a comma as the field separator) is shown below:

"1", "a string", "100.20"

"2", "a string containing a, comma", "102.20"

"3", "a string containing a" quote "," 102.20"

"4", "a string containing a", quote and comma "," 102.20"

If you specify OPTIONALLY, the enclosed by character is only used to enclose the CHAR and VARCHAR fields:

1, "a string", 100.20

2, "a string containing a, comma", 102.20

3, "a string containing a" quote ", 102.20

4, "a string containing a", quote and comma ", 102.20

Note that the enclosed by character in a field value is escaped by using the escaped by character as its prefix. Note that if you specify an empty escaped by value, the output may not be correctly read BY the load data infile. For example, if the escape character is empty, the output shown above is as follows. Note that the second field in the fourth row contains a comma following the quotation marks. It (incorrectly) seems to end the field:

1, "a string", 100.20

2, "a string containing a, comma", 102.20

3, "a string containing a" quote ", 102.20

4, "a string containing a", quote and comma ", 102.20

Fields escaped by controls how to write or read special characters. If the fields escaped by character is not empty, it is used to prefix the following characters on the output:

Fields escaped by character

FIELDS [OPTIONALLY] enclosed by character

The first character of fields terminated by and lines terminated by values.

ASCII 0 (in fact, the subsequent escape characters are written as ASCII0, rather than a zero-value byte)

If the fields escaped by character is empty, no character is ESCAPED. It may not be a good idea to specify an empty escape character, especially if the field value in your data contains any character in the table just given.

For input, if the fields escaped by character is not empty, the appearance of this character is stripped and subsequent characters are literally used as words

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.