Matlab导入整个文件夹目录下txt文档到数据库

来源:互联网 发布:域名后缀的区别 编辑:程序博客网 时间:2024/05/21 05:39

使用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 notnamelist  = 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 



原创粉丝点击