duanpu1111
2019-02-25 23:38
浏览 235
已采纳

如何将.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>

图片转代码服务由CSDN问答提供 功能建议

我有兴趣将这5000行.txt文件导入mysql数据库。

  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 |另一个组名称| 
 
   
 
  
 
  
 
 
 
 <  p>其中P表示该行表示“产品”表,B表示“品牌”表,G表示“组”。 我需要在数据库中分开使用它们。
如果只能用sql做它是不可能的,有一些方法我会得到我想用PHP的结果吗?   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongquexi1990 2019-02-26 03:41
    已采纳

    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

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongmi8980 2019-02-25 23:54

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题