Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL LOAD DATA INFILE - Loading a file with no primary key

I was trying to load a data file into mysql table using "LOAD DATA LOCAL INFILE 'filename' INTO TABLE 'tablename'".

The problem is the source data file contains data of every fields but the primary key is missing ('id' column). I have to add a unique id to each line of source data file otherwise the import will not go through.

Is there an option to ignore primary key in source file or auto increase it during the import?

It's already been set to a auto-increment primary key.

mysql> desc tablename;
+--------------------+--------------+------+-----+---------+----------------+
| Field              | Type         | Null | Key | Default | Extra          |
+--------------------+--------------+------+-----+---------+----------------+
| id                 | int(11)      | NO   | PRI | NULL    | auto_increment | 
...
like image 381
jack Avatar asked Nov 01 '09 12:11

jack


People also ask

How do you load a file into a MySQL table?

mysql> LOAD DATA LOCAL INFILE '/path/pet. txt' INTO TABLE pet; If you created the file on Windows with an editor that uses \r\n as a line terminator, you should use this statement instead: mysql> LOAD DATA LOCAL INFILE '/path/pet.

How do I insert selected columns from a CSV file to a MySQL database using load data infile?

The code is like this: LOAD DATA INFILE '/path/filename. csv' INTO TABLE table_name FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (column_name3, column_name5); Here you go with adding data to only two columns(you can choose them with the name of the column) to the table.

How do I import a CSV file into MySQL?

In the Format list, select CSV. Changing format-specific options. If the csv file is delimited by a character other than a comma or if there are other specifications to the csv files, we can change it in this portion. Click Go to start importing the csv file and the data will be successfully imported into MySQL.

What is Local_infile MySQL?

The local_infile system variable controls server-side LOCAL capability. Depending on the local_infile setting, the server refuses or permits local data loading by clients that request local data loading. By default, local_infile is disabled. (This is a change from previous versions of MySQL.)


1 Answers

Why not load into a table that has an auto-increment primary key?

create table MyTable (
    id integer auto_increment primary key,
    ...
)

You can specify the columns that will be imported after the table name:

LOAD DATA INFILE 'filename' INTO TABLE tablename (col1,col2,...);

If you don't specify the id column, MySQL won't read it from the file.

like image 133
Andomar Avatar answered Oct 03 '22 07:10

Andomar