1. 程式人生 > >Loading Data into a Table

Loading Data into a Table

not 默認 delete format txt文件 pre 電腦 var 想要

  • 在localhost中準備好了一個test數據庫和一個pet表:
    1. mysql> SHOW DATABASES;
      +--------------------+
      | Database           |
      +--------------------+
      | information_schema |
      | test               |
      +--------------------+
      2 rows in set (0.01 sec)
      
      mysql> USE test
      Database changed
      mysql> SHOW TABLES;
      +
      ----------------+ | Tables_in_test | +----------------+ | pet | +----------------+ 1 row in set (0.01 sec)
  • 在電腦中準備一個pet.txt文件,裏面包含想要導入到pet表的數據。(文件中一行代表一條數據)
  • 向pet表載入pet.txt中的數據:
    1. mysql> LOAD DATA LOCAL INFILE E:\Desktop\pet.txt INTO TABLE pet;
      ERROR 1148 (42000): The used command is
      not allowed with this MySQL version

      ERROR原因:服務器端,local_infile默認開啟,客戶端local_infile默認關閉,因此用的時候需要打開它

    2. mysql> SHOW VARIABLES like local_infile;
      +---------------+-------+
      | Variable_name | Value |
      +---------------+-------+
      | local_infile  | OFF   |
      +---------------+-------+
      1 row in set
      , 1 warning (0.04 sec)

      開啟local_infile:(開啟後,再次執行SHOW VARIABLES like ‘local_infile‘會看到Value為ON)

    3. mysql> SET GLOBAL local_infile=ON;
      Query OK, 0 rows affected (0.00 sec)

      重新載入:

    4. mysql> LOAD DATA LOCAL INFILE E:\Desktop\pet.txt INTO TABLE pet;
      ERROR 2 (HY000): File E:Desktoppet.txt not found (OS errno 2 - No such file or directory)

      ERROR原因:路徑應使用‘/‘ , 重新載入:

    5. mysql> LOAD DATA LOCAL INFILE E:/Desktop/pet.txt INTO TABLE pet;
      Query OK, 8 rows affected, 7 warnings (0.02 sec)
      Records: 8  Deleted: 0  Skipped: 0  Warnings: 7  

      載入完畢,查看載入成功後的pet表: ψ(`∇´)ψ

    6. mysql> select * from pet;
      +----------+--------+---------+------+------------+------------+
      | name     | owner  | species | sex  | birth      | death      |
      +----------+--------+---------+------+------------+------------+
      | Fluffy   | Harold | cat     | f    | 1993-02-04 | 0000-00-00 |
      | Claws    | Gwen   | cat     | m    | 1994-03-17 | 0000-00-00 |
      | Buffy    | Harold | dog     | f    | 1989-05-13 | 0000-00-00 |
      | Fang     | Benny  | dog     | m    | 1990-08-27 | 0000-00-00 |
      | Bowser   | Diane  | dog     | m    | 1979-08-31 | 1995-07-29 |
      | Chirpy   | Gwen   | bird    | f    | 1998-09-11 | 0000-00-00 |
      | Whistler | Gwen   | bird    |      | 1997-12-09 | 0000-00-00 |
      | Slim     | Benny  | snake   | m    | 1996-04-29 | 0000-00-00 |
      +----------+--------+---------+------+------------+------------+
      8 rows in set (0.00 sec

Loading Data into a Table