资源描述:
《matlab连接sql数据库》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、matlab连接SQL数据库1首先创建数据库,就不废话了。2建立ODBC数据源:控制面板->管理工具->ODBC数据源->用户DNS。如图点击“添加”旋转“SQLServer”,“完成”。数据源名称--编程时要用到,可任意命名。服务器选择自己指定的选择默认数据库,下一步下一步旋转SQLServer验证,完成。3编程(来自网络)这段程序已经过我验证。sourceName=input('EnterthesourceName:','s');%获取数据源的名称(dbtest)Timeout=logintimeout(5);
2、%允许登录连接时间最长为5sconn=database(sourceName,'sa','123');%获取数据库连接对象ping(conn)%测试数据库连接状态dbmeta=dmd(conn);%获取数据元对象t=tables(dbmeta,'tutorial');%获取cata为tutorial的表名[trow,tcolumn]=size(t);%获取返回数组的大小index=1;fori=1:trow%由于表中既包含了系统表格ifstrcmp(t{i,2},'TABLE')%又包含了用户表格,需要在其中tab
3、lename{1,index}=t{i,1};%找出用户表格,对t数组的每一行index=index+1;%的第二个元素判断是table则为用end%户表。endtabletosee=input('Whichonewouldyouwanttouse?','s');%获取欲查看的表格的名称sql=['select*from',tabletosee];%构造查询的sql语句curs=exec(conn,sql);%执行该sql语句setdbprefs('DataReturnFormat','cellarray');%设
4、定数据返回格式curs=fetch(curs);%获取结果集对象numrows=rows(curs);%获取返回数据的行数numcols=cols(curs);%获取返回数据的列数disp('--------------------------------------------------------------');%在屏幕中显示表格信息fprintf('InformationofTable%s.',tabletosee);disp('--------------------------------------
5、------------------------');fprintf('numberofrows=%d,numberofcolumns=%d',numrows,numcols);disp('FieldNametypeNametypeValuecolumnWidthnullable');fork=1:numcols%分别获取相关信息attributes=attr(curs,k);tableinfo{k,1}=attributes.fieldName;%获取字段名称tableinfo{k,2}=attributes.t
6、ypeName;%获取字段类型名tableinfo{k,3}=attributes.typeValue;%获取字段类型代码tableinfo{k,4}=attributes.columnWidth;%获取字段的宽度tableinfo{k,5}=attributes.nullable;%获取字段是否可空enddisp(tableinfo);%显示数据表的结构信息disp('-------------------------------------------------------------');fprintf('
7、DataofTable%s.',tabletosee);disp('--------------------------------------------------------------');fori=1:numcolsfprintf('%s',tableinfo{i,1});endfprintf('');tabledata=curs.data;%获取结果集对象的数据disp(tabledata);%显示数据表中的数据