Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table automatically according to input file in mysql

Tags:

mysql

I have a file with large number of columns and I want to input this file in mysql table.

The thing is if we have file with, say, 8 columns then we will first create table by -

CREATE TABLE `input` (
  `idInput` varchar(45) DEFAULT NULL,
  `row2` varchar(45) DEFAULT NULL,
  `col3` varchar(45) DEFAULT NULL,
  `col4` varchar(45) DEFAULT NULL,
  `col5` varchar(45) DEFAULT NULL,
  `col6` varchar(45) DEFAULT NULL,
  `col7` varchar(45) DEFAULT NULL,
  `col8` varchar(45) DEFAULT NULL
);

then we will input the file by -

LOAD DATA INFILE "FILE" INTO TABLE input;

But the thing is, I have file with 150 columns and I want to insert this file in mysql table automatically (so that I should not have to create table first). The first row of my file is header and it should be as column names in table and also each column and each row has different datatype.

So is there any easy way to do this so that after that I can do different things with this table?

I am using mysql command line client version 5.5.20 (windows 7).

like image 784
Vikas Avatar asked Feb 06 '12 12:02

Vikas


People also ask

Can you use to load data from a file into a table?

To read the file back into a table, use LOAD DATA . The syntax of the FIELDS and LINES clauses is the same for both statements. The mysqlimport utility provides another way to load data files; it operates by sending a LOAD DATA statement to the server.

Which statement can you use to load data from a file into a table MySQL?

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.

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.)

How do you populate a table in MySQL?

First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.


1 Answers

use phpmyadmin. It has the ability to create table base on the first line of the file and guess the table structure. Click "Import" link and select your file. Don't forget to select the Format to fit your file format, mostly CSV.

If the file is too big to fit into phpmyadmin, sometimes I "head" the file and use the head file in phpmyadmin to create the table, then import the file using the LOAD DATA command.

It makes my life easier.

like image 108
Ben Lin Avatar answered Oct 12 '22 18:10

Ben Lin