Python - mysql中匯入CSV資料 【學習筆記】

來源:互聯網
上載者:User

標籤:python   mysql   

<span style="font-size:18px;">匯出mysql> INSERT INTO test_main    -> SELECT 1, 'A' UNION ALL    -> SELECT 2, 'B' UNION ALL    -> SELECT 3, 'C';Query OK, 3 rows affected (0.01 sec)Records: 3  Duplicates: 0  Warnings: 0 mysql>mysql> select id, value    -> INTO OUTFILE 'f:/test_main.txt'    -> FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY ''''    -> LINES TERMINATED BY '\n'    -> FROM test_main;Query OK, 3 rows affected (0.01 sec)   匯入  資料檔案比目標表多欄位 mysql> LOAD DATA INFILE 'f:/test_main.txt'    -> INTO TABLE test_main6    -> FIELDS TERMINATED BY ','    -> OPTIONALLY ENCLOSED BY ''''    -> (@dummy, value);Query OK, 3 rows affected (0.00 sec)Records: 3  Deleted: 0  Skipped: 0  Warnings: 0 mysql> select * from test_main6;+-------+| value |+-------+| A     || B     || C     |+-------+3 rows in set (0.00 sec)  這裡的關鍵點, 在於那個   @dummy。對你而言, 如果檔案有 10列, 你只導 2 , 7 的話, 那就是 @dummy,列2,@dummy,@dummy,@dummy,@dummy,列7,@dummy,@dummy,@dummy</span>


第一部分, 是如何處理,  資料檔案中, 列的數量,  大於 表的數量的情況。


假設資料檔案如下: Book1.csv  編號,名稱,說明1,測試資料1,"測試CSV檔案中,有逗號"2,測試資料2,"測試CSV檔案中有""雙引號"""3,測試資料3,"測試CSV檔案中,有逗號和""雙引號"""4,測試資料4,普通資料  mysql> CREATE TABLE Test_Book1 (    ->   id    int,    ->   name  VARCHAR(10),    ->   data  VARCHAR(100)    -> );Query OK, 0 rows affected (0.05 sec)  下面的 lines terminated by '\r\n' 是 要求分行符號號,為 windows的換行下面的 ignore 1 lines是 忽略第一行的標題列。mysql> LOAD DATA INFILE 'f:/Book1.csv'    -> INTO TABLE Test_Book1    -> FIELDS TERMINATED BY ','    -> OPTIONALLY ENCLOSED BY '"'    -> lines terminated by '\r\n'    -> ignore 1 lines    -> (id, name, data);Query OK, 4 rows affected (0.00 sec)Records: 4  Deleted: 0  Skipped: 0  Warnings: 0 mysql> select * from test_book1;+------+-----------+--------------------------------+| id   | name      | data                           |+------+-----------+--------------------------------+|    1 | 測試資料1 | 測試CSV檔案中,有逗號           ||    2 | 測試資料2 | 測試CSV檔案中有"雙引號"        ||    3 | 測試資料3 | 測試CSV檔案中,有逗號和"雙引號" ||    4 | 測試資料4 | 普通資料                       |+------+-----------+--------------------------------+4 rows in set (0.00 sec)   對你而言, 你需要使用ignore 1 lines 忽略第一行的標題列。

第二部分, 是說明, 如何 排除掉標題列的情況。




Python - mysql中匯入CSV資料 【學習筆記】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.