1. 程式人生 > >Matlab匯入整個資料夾目錄下txt文件到資料庫

Matlab匯入整個資料夾目錄下txt文件到資料庫

使用Matlab將指定資料夾下所有txt文件資料匯入MySQL資料庫。

備忘:寫這個程式的目的是為了將同一目錄下的一百多個txt文件匯入資料庫。文字的命名都是類似的,名稱的最後四位數字用於區分不同文件。

文件內的資料格式:每列用空格分隔,每行用換行符分隔,都是純數字。

function importFolder2db(filedir)

% namelist  = dir('D:/myFolder/myDataset/*.txt');
% 讀取後namelist 的格式為
% name -- filename
% date -- modification date
% bytes -- number of bytes allocated to the file
% isdir -- 1 if name is a directory and 0 if not
namelist  = dir(filedir);
filedir(end-4:end) = [];

% 連線資料庫(需要指定資料庫名稱dbname、使用者名稱root和密碼password)
conn = database('dbname', 'root', 'password', ... 
    'com.mysql.jdbc.Driver', 'jdbc:mysql://localhost:3306/dbname')

% 挨個倒入指定txt文件到指定資料庫表格
for mt = 1:size(namelist,1)
    filename = namelist(mt).name;
    filename(end-3:end) = []
    addr = strcat(filedir, namelist(mt).name)
    
    % 按檔名稱和內部資料格式建立相應表格
    % strcat函式會自動去掉字串中的空格
    sql = ['create table ',filename, ...
        '(hour int not null, minute int not null, depart int not null,', ...
        ' arrival int not null, count int not null);']

    exec(conn,sql)

    % 將文字資料匯入相應表格(文字每一行內的資料以空格分隔)
    sql = ['load data local infile ''', addr, ...
        ''' into table ', filename, ...
        ' fields terminated by '' '' lines terminated by ''\n'';']

    exec(conn,sql)

    % 檢查匯入表格的總行數
    sql = ['select count(*) from ',filename,';']
    curs = exec(conn,sql);
    curs = fetch(curs);
    ress = curs.Data;
    ress = cell2mat(ress);
    
    %判斷ress是否為指定資料型別
    if(isa(ress,'double'))
        sprintf('Number of rows in this table: %d\n',ress);
    end
 

% 關閉資料庫連線
close(curs)
close(conn)

end