Load data of txt file into a database ignoring certain data? - java

Hi everyone I already know how to import a txt file to a database, But now I have two txt files with almost the same data on each file but the second file has one extra column and I dont need that column in my Db tables.
The two .txt files has the followig structure:
FILE 1
"GTVLL2R","WG1032","10321","WG1032X","0","Band2","9316","9716","385","479","10321","79","1","279","0","CHIP0","10321","430","321","2","0","3","ACTIVATED","FALSE","-",""
"GTVLL2R","WG1032","10322","WG1032Y","0","Band2","9316","9716","393","479","10322","79","1","279","0","CHIP256","10322","430","330","2","0","3","ACTIVATED","FALSE","-",""
FILE 2
"GTCEN4R","208","WG1084","10841","WG1084X","0","Band2","9316","9716","282","511","10841","111","1","311","0","CHIP0","430","330","10841","ACTIVATED","FALSE","-",""
"GTCEN4R","208","WG1084","10842","WG1084Y","0","Band2","9316","9716","299","511","10842","111","1","311","0","CHIP256","430","330","10842","ACTIVATED","FALSE","-",""
"GTCEN4R","208","WG1084","10843","WG1084Z","0","Band2","9316","9716","53","511","10843","111","1","311","0","CHIP512","430","330","10843","ACTIVATED","FALSE","-",""
"GTCEN4R","208","WG1084","10844","WG1084U","0","Band2","9295","9695","282","511","10844","111","1","311","0","CHIP0","430","330","10844","ACTIVATED","FALSE","-",""
Specifically, I dont need the column with the number 208 on the second file (I have to clear up that isn't always the same number). I don't know how to ignore that column when I do the query, the query i'm using is the following:
LOAD DATA LOCAL INFILE file_path INTO TABLE table_name
"FIELDS TERMINATED BY ','
"ENCLOSED BY '\"'
"LINES TERMINATED BY '\\r\\n'
"IGNORE 2 LINES"
I would be very grateful If you can help me. Thanks

I assume you are asking because you want both files loaded into the same table. There is not a way to skip the column using LOAD DATA INFILE, but accomplishing what you are trying to do is doable.
Create table temp1 -- layout of first file
Load date infile from file 1 into temp1
Create table temp2 - layout of second file
Load data infile from file 2 into temp2
Alter table temp2 drop column 208_column
Create table combined_table like temp1
Insert into combined_table select * from temp1
Insert into combined_table select * from temp2

Related

How to insert records from excel to database using spring jdbctemplate

I need to insert data from excel to database which looks:
Id Name Phone Joining Date Subject
1 A 11111 14-Mar-2001 Cse
2 B 22222 25-Dec-2016 IT
3 C 33333 12-Dec-2011 ECE
If I have to perform batch insert in a single table then I am able to do it using spring jdbctemplate(batchUpdate(...)).
But I want it to insert data in multiple tables e.g. 1st 3 columns in Table1, next 2 in Table2, next n in table3 like this way.
For reading data I am using POI API and after extracting data m keeping it in List of Map object which looks:
allObj=[{0=1.0, 1=A, 2=11111.0, 3=2001-3-14 0:0:0, 4=Cse}, {0=2.0, 1=B, 2=22222.0, 3=2016-12-25 0:0:0, 4=IT}, {0=3.0, 1=C, 2=33333.0, 3=2011-12-12 0:0:0, 4=ECE}]
How to perform this tasks? not asking full solution but a hint. Thanks
If coding is required then inform I am not posting it as it is lengthy and common.
EDITED:
Few didn't understand the Question!
I think u know batch update. I am using JdbcTemplate of spring.
suppose I have table T1 as:
Id|Name|Phone|Joining Date| Subject in Database(using MYSQL)
Now, I have an excel file with the corresponding values.I can read it and batch insert it into database by JdbcTemplate in that table.
But Now I have two table as T1: Id|Name|Phone
and T2: Joining Date| Subject
I have the same excel file.
NOW my question comes into the frame.
How to insert the values in two tables? If you get the question kindly remove your -ve vote.
LOAD DATA LOCAL INFILE
'C:\\temp\\file.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(#col1,#col2)
set
column1 = #col1,
column2 = #col2;
Above query for table1, run same for other tables by changing column_names accordingly.

Java insert bit data to Mysql [duplicate]

I have an unnormalized events-diary CSV from a client that I'm trying to load into a MySQL table so that I can refactor into a sane format. I created a table called 'CSVImport' that has one field for every column of the CSV file. The CSV contains 99 columns , so this was a hard enough task in itself:
CREATE TABLE 'CSVImport' (id INT);
ALTER TABLE CSVImport ADD COLUMN Title VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN Company VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN NumTickets VARCHAR(256);
...
ALTER TABLE CSVImport Date49 ADD COLUMN Date49 VARCHAR(256);
ALTER TABLE CSVImport Date50 ADD COLUMN Date50 VARCHAR(256);
No constraints are on the table, and all the fields hold VARCHAR(256) values, except the columns which contain counts (represented by INT), yes/no (represented by BIT), prices (represented by DECIMAL), and text blurbs (represented by TEXT).
I tried to load data into the file:
LOAD DATA INFILE '/home/paul/clientdata.csv' INTO TABLE CSVImport;
Query OK, 2023 rows affected, 65535 warnings (0.08 sec)
Records: 2023 Deleted: 0 Skipped: 0 Warnings: 198256
SELECT * FROM CSVImport;
| NULL | NULL | NULL | NULL | NULL |
...
The whole table is filled with NULL.
I think the problem is that the text blurbs contain more than one line, and MySQL is parsing the file as if each new line would correspond to one databazse row. I can load the file into OpenOffice without a problem.
The clientdata.csv file contains 2593 lines, and 570 records. The first line contains column names. I think it is comma delimited, and text is apparently delimited with doublequote.
UPDATE:
When in doubt, read the manual: http://dev.mysql.com/doc/refman/5.0/en/load-data.html
I added some information to the LOAD DATA statement that OpenOffice was smart enough to infer, and now it loads the correct number of records:
LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
But still there are lots of completely NULL records, and none of the data that got loaded seems to be in the right place.
Use mysqlimport to load a table into the database:
mysqlimport --ignore-lines=1 \
--fields-terminated-by=, \
--local -u root \
-p Database \
TableName.csv
I found it at http://chriseiffel.com/everything-linux/how-to-import-a-large-csv-file-to-mysql/
To make the delimiter a tab, use --fields-terminated-by='\t'
The core of your problem seems to be matching the columns in the CSV file to those in the table.
Many graphical mySQL clients have very nice import dialogs for this kind of thing.
My favourite for the job is Windows based HeidiSQL. It gives you a graphical interface to build the LOAD DATA command; you can re-use it programmatically later.
Screenshot: "Import textfile" dialog
To open the Import textfile" dialog, go to Tools > Import CSV file:
Simplest way which I have imported 200+ rows is below command in phpmyadmin sql window
I have a simple table of country with two columns
CountryId,CountryName
here is .csv data
here is command:
LOAD DATA INFILE 'c:/country.csv'
INTO TABLE country
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
Keep one thing in mind, never appear , in second column, otherwise your import will stop
I Used this method to import more than 100K records (~5MB) in 0.046sec
Here's how you do it:
LOAD DATA LOCAL INFILE
'c:/temp/some-file.csv'
INTO TABLE your_awesome_table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(field_1,field_2 , field_3);
It is very important to include the last line , if you have more than one field i.e normally it skips the last field (MySQL 5.6.17)
LINES TERMINATED BY '\n'
(field_1,field_2 , field_3);
Then, assuming you have the first row as the title for your fields, you might want to include this line also
IGNORE 1 ROWS
This is what it looks like if your file has a header row.
LOAD DATA LOCAL INFILE
'c:/temp/some-file.csv'
INTO TABLE your_awesome_table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(field_1,field_2 , field_3);
phpMyAdmin can handle CSV import. Here are the steps:
Prepare the CSV file to have the fields in the same order as the MySQL table fields.
Remove the header row from the CSV (if any), so that only the data is in the file.
Go to the phpMyAdmin interface.
Select the table in the left menu.
Click the import button at the top.
Browse to the CSV file.
Select the option "CSV using LOAD DATA".
Enter "," in the "fields terminated by".
Enter the column names in the same order as they are in the database table.
Click the go button and you are done.
This is a note that I prepared for my future use, and sharing here if someone else can benefit.
If you are using MySQL Workbench (currently 6.3 version) you can do this by:
Right click on "Tables";
Chose Table Data Import Wizard;
Chose your csv file and follow the instructions (JSON also could be used);
The good thing is that you can create a new table based on the csv file you want to import or load data to an existing table
You can fix this by listing the columns in you LOAD DATA statement. From the manual:
LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata (col1,col2,...);
...so in your case you need to list the 99 columns in the order in which they appear in the csv file.
Try this, it worked for me
LOAD DATA LOCAL INFILE 'filename.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' ENCLOSED BY '"' IGNORE 1 ROWS;
IGNORE 1 ROWS here ignores the first row which contains the fieldnames. Note that for the filename you must type the absolute path of the file.
I see something strange. You are using for ESCAPING the same character you use for ENCLOSING. So the engine does not know what to do when it founds a '"' and I think that is why nothing seems to be in the right place.
I think that if you remove the line of ESCAPING, should run great. Like:
LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
Unless you analyze (manually, visually, ... ) your CSV and find which character uses for escape. Sometimes is '\'. But if you do not have it, do not use it.
The mysql command line is prone to too many problems on import. Here is how you do it:
use excel to edit the header names to have no spaces
save as .csv
use free Navicat Lite Sql Browser to import and auto create a new table (give it a name)
open the new table insert a primary auto number column for ID
change the type of the columns as desired.
done!
Yet another solution is to use csvsql tool from amazing csvkit suite.
Usage example:
csvsql --db mysql://$user:$password#localhost/$database --insert --tables $tablename $file
This tool can automatically infer the data types (default behavior), create table and insert the data into the created table. --overwrite option can be used to drop table if it already exists. --insert option — to populate the table from the file.
To install the suite
pip install csvkit
Prerequisites: python-dev, libmysqlclient-dev, MySQL-python
apt-get install python-dev libmysqlclient-dev
pip install MySQL-python
In case if you using Intellij
https://www.jetbrains.com/datagrip/features/importexport.html
I use mysql workbench to do the same job.
create new schema
open newly created schema
right click on "Tables" and select "Table Data Import Wizard"
give the csv file path and table name and finally configure your column type because the wizard set default column type based on their values.
Note: take a look at mysql workbench's log file for any errors by using "tail -f [mysqlworkbenchpath]/log/wb*.log"
How to import csv files to sql tables
Example file: Overseas_trade_index data CSV File
Steps:
Need to create table for overseas_trade_index.
Need to create columns related to csv file.
SQL Query:
( id int not null primary key auto_increment,
series_reference varchar (60),
period varchar (60),
data_value decimal(60,0),
status varchar (60),
units varchar (60),
magnitude int(60),
subject text(60),
group text(60),
series_title_1 varchar (60),
series_title_2 varchar (60),
series_title_3 varchar (60),
series_title_4 varchar (60),
series_title_5 varchar (60),
);
Need to connect mysql database in terminal.
=>show databases;
=>use database;
=>show tables;
Please enter this command to import the csv data to mysql tables.
load data infile '/home/desktop/Documents/overseas.csv' into table trade_index fields terminated by ',' lines terminated by '\n' (series_reference,period,data_value,status,units,magnitude,subject,series_title1,series_title_2,series_title_3,series_title_4,series_title_5);
Find this overseas trade index data on sqldatabase:
select * from trade_index;
If you are using a windows machine with Excel spreadsheet loaded, the new mySql plugin to Excel is phenomenal. The folks at Oracle really did a nice job on that software. You can make the database connection directly from Excel. That plugin will analyse your data, and set up the tables for you in a format consistent with the data. I had some monster big csv files of data to convert. This tool was a big time saver.
http://dev.mysql.com/downloads/windows/excel/
You can make updates from within Excel that will populate to the database online. This worked exceedingly well with mySql files created on ultra inexpensive GoDaddy shared hosting. (Note when you create the table at GoDaddy, you have to select some off-standard settings to enable off site access of the database...)
With this plugin you have pure interactivity between your XL spreadsheet and online mySql data storage.
I know that my answer is late, but I'd like to mention a few other ways to do it.
The easiest one is using command line. The steps will be the following:
Accessing the MySQL CLI by entering the below command:
mysql -u my_user_name -p
Creating a table in the database
use new_schema;
CREATE TABLE employee_details (
id INTEGER,
employee_name VARCHAR(100),
employee_age INTEGER,
PRIMARY KEY (id)
);
Importing the CSV file into a table. We can either mention the file path or store the file in the default directory of the MySQL server.
LOAD DATA INFILE 'Path to the exported csv file'
INTO TABLE employee_details
FIELDS TERMINATED BY ','
IGNORE 1 ROWS;
It's the only one of many solutions, I found it in this tutorial
If loading CSV files into MySQL database is your daily task, then it'll be better to automate this process. In this case you can use some 3rd-party tools that allows you to load data in schedule.
PHP Query for import csv file to mysql database
$query = <<<EOF
LOAD DATA LOCAL INFILE '$file'
INTO TABLE users
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(name,mobile,email)
EOF;
if (!$result = mysqli_query($this->db, $query))
{
exit(mysqli_error($this->db));
}
**Sample CSV file data **
name,mobile,email
Christopher Gritton,570-686-3439,ChristopherKGritton#inbound.plus
Brandon Wilson,541-309-5149,BrandonMWilson#inbound.plus
Craig White,516-795-8065,CraigJWhite#inbound.plus
David Whitney,713-214-3966,DavidCWhitney#inbound.plus
Here is sample excel file screen shot:
Save as and choose .csv.
And you will have as shown below .csv data screen shot if you open using notepad++ or any other notepad.
Make sure you remove header and have column alignment in .csv as in mysql Table.
Replace folder_name by your folder name
LOAD DATA LOCAL INFILE
'D:/folder_name/myfilename.csv'
INTO TABLE mail
FIELDS TERMINATED BY ','
(fname,lname ,email, phone);
If big data, you can take coffee and have it load!.
Thats all you need.
Change servername,username, password,dbname,path of your file, tablename and the field which is in your database you want to insert
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bd_dashboard";
//For create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$query = "LOAD DATA LOCAL INFILE
'C:/Users/lenovo/Desktop/my_data.csv'
INTO TABLE test_tab
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(name,mob)";
if (!$result = mysqli_query($conn, $query)){
echo '<script>alert("Oops... Some Error occured.");</script>';
exit();
//exit(mysqli_error());
}else{
echo '<script>alert("Data Inserted Successfully.");</script>'
}
?>
I did it in simple way using phpmyadmin. I followed the steps by #Farhan but all data were eltered in single column.
How I did:
Created a CSV file and deleted the header row with column names. Kept only data.
I created a table with column names matching the csv columns.
Remember to assign appropriate types to each column.
I just selected the import and went to import tab.
In browse I selected the CSV file and kept all options as it is.
To my surprise all the data got imported successfully in their appropriate columns.
When executing MySQL Query to import CSV I was getting error
'Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement'
So I moved file to secure file location
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/Orders.csv'
INTO TABLE orderdetails.orders
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
Where location of file is 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/Orders.csv' this is because, I moved my CSV file to 'secure_file_priv' location otherwise I was getting above error
You can get your secure_file_priv using query SHOW VARIABLES LIKE "secure_file_priv";
Source: Import CSV file to MySQL (Query or using Workbench)

Merge values to table from Java

I have a java program that reads a csv file line by line and does MERGE in the table using the Merge statement provided by DB2.
For example, If i have a 1000 lines in CSV it would run the executeUpdate 1000 times.
My challenge is that i run this script every hour so there is a possibility that new entries would come into the csv file or values would get updated or rows might be deleted (sometimes the row will come again in future)
I think i am doing the insert if not exist and update if exist part correct but i am not sure how do i do the delete part for rows that were inserted in the past but no longer in the latest csv file ?
Also what would be an ideal situation here to avoid doing 1000 insert statement do i use prepared statement ? Can someone give me an example ?
String sql_merge = " MERGE INTO IM4BMX.IEMCOMPUTER_DETAILS AS A USING (VALUES ('"+ComputerID+"', '"+Environment+"')) AS A_TMP ( ComputerID , Environment) ON A.ComputerID = A_TMP.ComputerID WHEN MATCHED THEN UPDATE SET ComputerID = '"+ComputerID+"', Environment = '"+Environment+"' WHEN NOT MATCHED THEN INSERT ( ComputerID , Environment ) VALUES (A_TMP.ComputerID, A_TMP.Environment ) ELSE IGNORE ";
stmt.executeUpdate(sql_merge);
Try adding a when not matched clause to your query.
Ex. WHEN NOT MATCHED
THEN DELETE
If you CSV file contains data that does not match what is in the DB then it should delete that row.
Look at this link for further information.
Merge Statement Explained

Import csv file to populate data in a table in Netbeans

I am very new to Java and Netbeans.I am trying to populate my table created in my database with data but the csv file contains about 1000 odd entries.Is there a way in which i can just import the data to their columns.
Any help would be appreciated.
I am assuming that you are using JavaDB that comes bundled with Netbeans (to be more accurate: it's included with the JDK).
You can use the import table command: SYSCS_UTIL.SYSCS_IMPORT_TABLE.
Check: https://db.apache.org/derby/docs/10.1/ref/rrefimportproc.html.
As an example:
go here: http://www.andrewpatton.com/countrylist.html and download Country List downloadable as CSV.
create a table which you can name COUNTRY and as columns the names in the first line of the downloaded csv file. First column name: SortOrder should be the primary key. Add the rest columns as VarChar columns with size 100. Do the same for the rest but be careful not to mess with the order of the columns as you cannot change it later. What I mean is that the order of the columns that you create in your table, should follow the order of the columns in the csv file. For example "Sort Order" should be created first, then create,"Common Name", then "Formal Name" ....
then remove the first line from the csv file (the column names)
execute the following command CALL SYSCS_UTIL.SYSCS_IMPORT_TABLE (null,'COUNTRY','c:\countrylist.csv',',','"',null,0);
select the table that you created , right click it and click View data.
Thats it !
If you are using MySQL check:
How to import CSV file to MySQL table
How to import a csv file into MySQL workbench?

How to get the database backup into a csv file or .sql file without using runtime commands from java

My require ment is i need to get the database tables data into a single csv file or .sql file without using any mysqldump commands in java
You can simply fetch data (select * from table) than create a csv or sql file.
For csv file, append ',' between fields and append '\n' at end of line
For sql file, append constant prefix like 'insert into table (', and other string values similar to csv.
It looks like DbUnit supports CSV files. It may help with this.

Categories

Resources