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

 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章