importing csv file into mysql server but only 1st row is inserting and with wrong entries - mysql

Goal: I have to import CSV file into MySQL server
Problem: Only 1st row is inserting and that too with wrong entry.
formant of my csv file is:
lifelock,LifeLock,,web,Tempe,AZ,1-May-07,6850000,USD,b
lifelock,LifeLock,,web,Tempe,AZ,1-Oct-06,6000000,USD,a
lifelock,LifeLock,,web,Tempe,AZ,1-Jan-08,25000000,USD,c
mycityfaces,MyCityFaces,7,web,Scottsdale,AZ,1-Jan-08,50000,USD,seed
flypaper,Flypaper,,web,Phoenix,AZ,1-Feb-08,3000000,USD,a
query to create sql table:
create table fund(permalink varchar(20), company varchar(20), numEmps int, category varchar(15),
city varchar(20),state varchar(15),fundedDate Date,raisedAmt int, raisedCurrency longtext,round longtext);
query to import csv file:
load data infile '/var/lib/mysql-files/TechCrunchcontinentalUSA.csv' into table fund fields terminated by ','
lines terminated by '\n' (permalink, company, #numEmps , category , city ,state, #funded, #raised, raisedCurrency ,round )
set numEmps=cast(#emps as unsigned), raisedAmt = cast(#raised as unsigned), fundedDate =STR_TO_DATE(#funded, '%d-%b-%Y') ;
Output image

Is your primary key set to AUTO_INCREMENT? Also, check if your csv file has newline separator for each line. Sometimes, csv column data can be too big to fit in to your defined db column say your are defining your city column to hold a value of varchar(20) but in csv file you have an instance where city is more than 20 characters.
You can always validate your csv using this online tool (make sure you don't have any sensitive data as it is a third party tool)
Alternatively, try this too if your csv file and table name are same:
mysqlimport --lines-terminated-by='\n' --fields-terminated-by=',' --fields-enclosed-by='"' --verbose --local db_name TechCrunchcontinentalUSA.csv
Provide username and passwords flags -uroot -proot if you have one setup.

sql query
load data infile '/var/lib/mysql-files/TechCrunchcontinentalUSA.csv' into table fund fields terminated by ','
lines terminated by '\r' (permalink, company, #numEmps , category , city ,state, #funded, #raised, raisedCurrency ,round )
set numEmps=cast(#emps as unsigned),fundedDate =STR_TO_DATE(#funded, '%d-%b-%y'), raisedAmt = cast(#raised as unsigned) ;
I have changed the line terminator from \n to \r and changed the date from %d-%b-%y to %d-%b-%y because in date Y takes 4 digits as year i.e., 2007 as year and in y it takes 2 digit year i.e., 07.
For date format specifier visit here.

Related

Error in saving csv to MySQL table due to NULL values

I have the data saved in my csv excel. The data have some null value in row and column. I want to save this data into my database in MySQL. But null value is causing problem in saving the data to MySQL. This is the query for creating the table -
create table student (
Std_ID int,
Roll_NO int,
First_Name varchar(10) NOT NULL,
Last_Name varchar(10),
Class int,
constraint test_student primary key (Std_ID)
);
...and it ran successfully. Now I want to save my data from csv to this table using the query -
load data infile 'C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads\\new.csv' into table student fields terminated by ',' lines terminated by '\n' ignore 1 lines;
...and is giving me the error msg -
ERROR 1366 (HY000): Incorrect integer value: '' for column 'XXX' at row X.
For the reference you can use this data.
The same can be find below.
LOAD DATA INFILE 'C:\\ProgramData\\MySQL\\MySQL Server 8.0\\Uploads\\new.csv'
INTO TABLE student
FIELDS TERMINATED BY ','
LINES TERMINATED by '\n'
IGNORE 1 LINES
-- specify columns, use variables for the columns where incorrect value may occur
(Std_ID, #Roll_NO, First_Name, Last_Name, #Class)
-- use preprocessing, replace empty string with NULL but save any other value
SET Roll_NO = NULLIF(#Roll_NO, ''),
Class = NULLIF(#Class, '');
If some column in CSV is empty string then NULL value will be inserted into according column of the table.
Std_ID is not preprocessed because it is defined as PRIMARY KEY, and it cannot be NULL.
UPDATE
OP provides source file sample. Viewing it in HEX mode shows that the file is Windows-style text file, and hence the lines terminator is '\r\n'. After according edition the file is imported successfuly.

Date columns (datatype -timestamp) not imported correctly from csv into MySql

I am trying to import data from a csv file into MySQL using LOAD DATA LOCAL INFILE. All columns except the date columns which have timestamp as their datatype are imported correctly. I am getting the error 1265: data truncated for date column and it inserts 0000-00-00 00:00:00 for all values.This has been asked before but I did not find a perfect solution for this. I have also tried various solutions posted for this type of question but none have worked for me.
table create statement :
CREATE TABLE MySchema.response
(
`id` int,
`version` int,
`name` varchar(500),
`date_created` timestamp,
`last_updated` timestamp,
`count` int,
);
loading data into table:
LOAD DATA LOCAL INFILE 'C:/response.csv'
INTO TABLE MySchema.response
FIELDS TERMINATED BY ',' optionally ENCLOSED by '"'
ignore 1 lines
Sample Data in CSV file
id version name date_created last_updated count
1, 0, xyz, 5/3/2013 1:18, 5/3/2013 1:18, 2
2, 0, abc, 5/3/2013 1:18, 5/3/2013 1:18, 1
Date columns in your sample are not in MySQL's default format and thus are not identified as dates. You need to try something like the following, in order to state how the dates should be interpreted:
LOAD DATA LOCAL INFILE 'C:/response.csv'
INTO TABLE MySchema.response
FIELDS TERMINATED BY ',' optionally ENCLOSED by '"'
IGNORE 1 lines
(id, version, name, #date_created, #last_updated, count)
SET date_created = STR_TO_DATE(#date_created, '%d/%c/%Y %k:%i'),
last_updated = STR_TO_DATE(#last_updated, '%d/%c/%Y %k:%i');
Check MySQL date format documentation for specifiers that suit your case (probably the ones I added in the sample above).

Load csv file into mysql database

I'm trying to load a big CSV file into mysql but couldn't find out why it fails.
My CSV file looks like this:
_id,"event","unit","created","r1","r2","r3","r4","space_id","owner_id","name","display_name","users__email"
565ce313819709476d7eaf0e,"create",3066,"2015-12-01T00:00:19.604Z","563f592dd6f47ae719be8b38","3","13","7","55ecdd4ea970e6665f7e3911","55e6e3f0a856461404a60fc1","household","household","foo.bar#ace.com"
565ce350819709476d7eaf0f,"complete",3067,"2015-12-01T00:01:19.988Z","21","","","","55e6df3ba856461404a5fdc9","55e6e3f0a856461404a60fc1","Ace","Base","foo.bar#ace.com"
565ce350819709476d7eaf0f,"delete",3067,"2015-12-01T00:01:19.988Z","21","","","","55e6df3ba856461404a5fdc9","55e6e3f0a856461404a60fc1","Ace","Base","foo.bar#ace.com"
565ce350819709476d7eaf0f,"update",3067,"2015-12-01T00:01:19.988Z","21","","","","55e6df3ba856461404a5fdc9","55e6e3f0a856461404a60fc1","Ace","Base","foo.bar#ace.com"
And my code to load the file into mysql is this one:
CREATE DATABASE IF NOT EXISTS analys;
USE analys;
CREATE TABLE IF NOT EXISTS event_log (
_id CHAR(24) NOT NULL,
event_log VARCHAR(255),
unit CHAR(4),
created VARCHAR(255),
r1 VARCHAR(255),
r2 VARCHAR(255),
r3 VARCHAR(255),
r4 VARCHAR(255),
space_id VARCHAR(255),
owner_id VARCHAR(255),
name VARCHAR(255),
display_name VARCHAR(255),
users__email VARCHAR(255),
PRIMARY KEY (_id)
)
LOAD DATA INFILE 'audits.export.csv'
INTO TABLE event_log
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n\r'
IGNORE 1 ROWS;
Everything is fine, including the query but I get NULL in every column (only one row).
Here is the Action Output:
22:31:21 LOAD DATA INFILE 'audits.export.csv' INTO TABLE event_log FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n\r' IGNORE 1 ROWS 0 row(s) affected Records: 0 Deleted: 0 Skipped: 0 Warnings: 0 0.156 sec
I tried to tweak the table and the load query but it doesn't work
I'm on Windows 7, using Mysql 5.6 and Workbench.
I heard about GUI solution or Excel connectors here (Excel Connector) but I prefer to do it programmaticaly as I need to reuse the code.
Any help? I couldn't solve the problem with similar posts on Stackoverflow.
This doens't seem a valid newline:
LINES TERMINATED BY '\n\r'
change to:
LINES TERMINATED BY '\r\n'
Or only one of them (could be single \n or \r depending on the system, or the software that created the csv file).
Because some might come here wanting to know how to do this with MySQL Workbench:
Save CSV data to a file, for example foo.csv
Open MySQL Workbench
Choose/Open a MySQL Connection
Right-click on a schema in the Object Browser (left Navigator)
Choose "Table Data Import Wizard"
Select the CSV file, which is foo.csv in our example
Follow the wizard; many configuration options are available, including the separator
When finished, the CSV data will be in a new or existing table (your choice)
For additional information, see the documentation titled Table Data Export and Import Wizard.
I just tested this in the example data provided in the question, and it worked.

How to convert Date on MySQL (variable error)

I have created this table on MySQL :
create table Apolo(
Date date,
Name varchar(50)
);
I have imported an excel file :
LOAD DATA LOCAL INFILE 'C:/Users/File.csv'
INTO TABLE Apolo
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 10 ROWS
(#Date, Name);
set Date=str_to_date(#Date,'%d/%m/%Y');
and I get the error :
Error Code: 1193. Unknown system variable 'Date'
If I do not put this line :
set Date=str_to_date(#Date,'%d/%m/%Y');
I do not get the error but if I try to use :
select count(*) from Apolo where Date='03/09/2015';
it does not work. So the format is not recognisable.
The date to insert into mysql database should be in the format
YYYY-MM-DD
Example: 2015-02-18
So change the date in csv file to the above specified format and try ..
Check your Date column values in database. By default date format in mysql database is Y-m-d
Do you have values in this format.
Take the semi-colon out of this line
(#Date, Name);
The set should be in the same command. Watch out for the fact that you have a field name that is a reserved word - you may need to escape it.

using linux shell script insert dump data to Mysql

i use below script for insert data to sql from textpad.
#!/bin/bash
mysql --utest -ptest test << EOF
LOAD DATA INFILE 'test.txt'
INTO TABLE content_delivery_process
FIELDS TERMINATED BY ',';
EOF
in my test file i have a format like,
cast , date , name , buy
i can insert but i need format like below,
S.NO | date | name | buy | cast
You can specify the columns you want to import:
From the MySQL Manual:
MySQL LOAD DATA INFILE
The following example loads all columns of the persondata table:
LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata;
By default, when no column list is provided at the end of the LOAD
DATA INFILE statement, input lines are expected to contain a field for
each table column.
If you want to load only some of a table's columns, specify a column
list:
LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata (col1,col2,...);
You must also specify a column list if the order of the fields in the
input file differs from the order of the columns in the table.
Otherwise, MySQL cannot tell how to match input fields with table
columns.
You would include "FIELDS TERMINATED BY '|';" at the end to import data delimited with a '|' symbol.
Hope this helps.
create table [YOUR TABLE] ( `S.NO` INT AUTO_INCREMENT, date DATETIME, name VARCHAR(50), buy VARCHAR(50), cast VARCHAR(50));
Load data local infile 'test.txt' ignore into table [YOUR TABLE] fields terminated by ',' lines terminated by '\n'(cast , date , name , buy);