1. 程式人生 > >Mysql資料的匯入和資料的匯出

Mysql資料的匯入和資料的匯出

資料匯入

    作用:  把檔案系統的內容匯入到資料庫中
    語法:
        load data infile"檔名"
        into table 表名
        fields terminated by "分隔符"
        lines terminated by "\n"

步驟:

  1. 在資料庫中建立相應的表
  2. 將檔案拷貝到資料庫預設搜尋路徑中                                                                                                                                             1)檢視預設搜尋路徑                                                                                                                                                            2)拷貝路徑
  3. 執行書籍匯入語句

示例:

將scoretable.csv檔案匯入到資料庫的表中
    1.在資料庫中建立對應的表
    create table scoretab(
    id int,
    name varchar(15),
    score float(5,2),
    number bigint,
    class char(7)
    );
    2.把檔案拷貝到資料庫的預設搜尋路徑中
        1)檢視預設搜尋路徑
        show variables like "secure_file_priv"

        路徑為/var/lib/mysql-files/
        2)拷貝路徑
        sudo cp ~/scoretable.csv /var/lib/mysql-files/

    3.執行資料匯入語句
    load data infile "/var/lib/mysql-files/scoretable.csv"
    into table scoretab
    fields terminated by ","
    lines terminated by "\n";

檔案許可權:
        rwxrw-rw- 1  tarena tarena scoretable.csv
                             所有者  所屬組

        rwx : tarena使用者
        rw- : 同組其他使用者
        rw- : 其他組的其他使用者(mysql使用者)

        r ->4
        w ->2
        x ->1
        chmod 666 檔名 rw-r--r--

Excel表格如何轉化為csv檔案:

            開啟Excel檔案 -> 另存為 -> csv(逗號分隔)

更改檔案編碼格式:

            用記事本/編輯器 開啟,檔案 -> 另存為 ->選擇編碼

資料匯出

作用:

         將資料庫中的表的記錄匯入到系統檔案中

語法格式:

        select ... from 表名
        into outfile "/var/lib/mysql-files/檔名"
        fields terminated by "分隔符"
        lines terminated by "\n";

示例:

把MOSHOU庫下的sanguo表英雄的姓名、攻擊值、國家匯出來sanguo.txt
     select name,gongji,country from MOSHOU.sanguo
     into outfile "/var/lib/mysql-files/sanguo.txt"
     fields terminated by " "
     lines terminated by "\n";