I have a csv with a range of info that I need load into different mysql tables is there a away to do that?
Data for table 1 would be at the top of the csv between rows 1 and 10 and would have the data heading in column A and the data in Column B Like this:
The below that would be the data for table 2 which would look like this:
Any ideas?
Thanks
You can separate the data in separate files and then use mysqlimport.
If you are not confident with that then you can use MySqlWorkBench . It has CSV import facility.
You can create a temporary table, load all the data from the csv into this temporary table and add to your table from there based on a key (line for example) from the temporary table.
Something like this.
Create the temporary table.
CREATE TEMPORARY TABLE tmp
(
line int AUTO_INCREMENT PRIMARY KEY,
field1 varchar(255),
field2 varchar(255),
field3 varchar(255)
);
Load the data.
LOAD DATA LOCAL INFILE 'file.txt' INTO TABLE tmp
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(@field1, @field2, @field3)
SET field1 = @field1,
field2 = @field2,
field3 = @field3;
So if you want to insert the data from lines 5 to 10 into the table1.
INSERT INTO table1
SELECT field1, field2, field3
FROM tmp
WHERE line >= 5 AND line <= 10
Add the rest of the lines into a different table
INSERT INTO table2
SELECT field1, field2, field3
FROM tmp
WHERE line > 10
If you know after how many lines you will be wanting to change the table, you could do something like (source php.net):
...
$table_one_data = array();
$table_two_data = array();
$row = 0;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row++
if ($row < 1000) {
array_push($table_one_data, $data);
} else {
array_push($table_two_data, $data);
}
}
fclose($handle);
}
....
You could also trigger this through data in the CSV file:
...
$table_one_data = array();
$table_two_data = array();
$field = 0;
$trigger = "table2";
$tableChange = false;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($data[field] == $trigger) {
tableChange = true;
}
if (!$tableChange) {
array_push($table_one_data, $data);
} else {
array_push($table_two_data, $data);
}
}
fclose($handle);
}
....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.