如何将.txt文件导入到不同表中的mysql数据库中
I am interested to import this 5000 line .txt file into a mysql database.
P|1|A PRODUCT|1|0002000|204|123|
P|2|ANOTHER PRODUCT|10000371|0001990|055|031|
B|055|A BRAND NAME|
B|204|ANOTHER BRAND NAME|
G|123|GROUP NAME|
G|031|ANOTHER GROUP NAME|
Where P means that line refers to a "Product" table, B means "Brand" table and G means "Group". I need them separatedly in the database. If it's impossible to do it only with sql, there is some way i'll get the result I want using PHP?
</div>
我有兴趣将这5000行.txt文件导入mysql数据库。 p>
p>
P | 1 | A PRODUCT | 1 | 0002000 | 204 | 123 |
\ n P | 2 |另一个产品| 10000371 | 0001990 | 055 | 031 |
B | 055 |品牌名称|
B | 204 |另一个品牌名称|
G | 123 | GROUP NAME |
G | 031 |另一个组名称|
code> pre>
div>
div>
其中P表示该行表示“产品”表,B表示“品牌”表,G表示“组”。 我需要在数据库中分开使用它们。
如果只能用sql做它是不可能的,有一些方法我会得到我想用PHP的结果吗? p>
div>
the php explode will do the job for you, here is how
$data = file_get_contents('data.txt')
// make an array for each line
$lines = explode('/n', $data)
foreach ($lines as $line) {
// Make array for each part of the line
$eline = explode('|', $line) ;
// $eline[0] is first part that have b or g or p
if ($eline[0] == 'B') {
// the sql code for brands
}
}
if you want i can complete the full code for you just tell me what the sql querys
It would be easiest if the file was separated by type. I'd use grep because its there already and saves writing the same functionality in php:
grep ^P file.txt > P.txt
grep ^G file.txt > G.txt
grep ^B file.txt > B.txt
LOAD DATA LOCAL INFILE can be used to import each individual file into its own table. Ensure mysql
client is started with --local-infile
to allow it to pass the file.