www.gusucode.com > database 案例源码程序 matlab代码 > database/ImportDataUsingDatabaseDatastoreExample.m

    %% Import Data Using a |DatabaseDatastore| Object
% This example shows how to import data into MATLAB(R) using a
% |DatabaseDatastore| object. To access collections of data stored in a
% relational database, you can use a |<docid:database_ug.bufomil
% DatabaseDatastore>| object. After creating a |DatabaseDatastore| object,
% you can preview data, read data in chunks, and read every record in the
% data set.
%
% To analyze large data, you can run algorithms on large data sets using a
% tall array. For an example of using a |DatabaseDatastore| object with
% tall arrays, see <docid:database_examples.example-ex44807149>.
% Alternatively, you can write a MapReduce algorithm that defines the
% chunking and reduction of the data. For an example, see
% <docid:database_examples.example-ex81756746>. For more MapReduce
% examples, see <docid:import_export.buhnu4_>.

%% Create |DatabaseDatastore| Object
% Using a JDBC driver, create a database connection |conn| to a
% Microsoft(R) SQL Server(R) database with Windows(R) authentication.
% Specify a blank user name and password. The code assumes that you
% are connecting to a database |toy_store|, a database server |dbtb04|, and
% port number |54317|.

conn = database('toy_store','','','Vendor','Microsoft SQL Server',...
    'Server','dbtb04','PortNumber',54317,'AuthType','Windows');

%% 
% Create a |DatabaseDatastore| object |dbds| using the database connection
% |conn| and SQL query |sqlquery|. This SQL query retrieves all data from
% the table |airlinesmall|. 

sqlquery = 'select * from airlinesmall';

dbds = databaseDatastore(conn,sqlquery);

%% Preview Data in |DatabaseDatastore| Object
% Preview the first eight records in the data set returned by executing
% |sqlquery|.

preview(dbds)

%% Read Data in |DatabaseDatastore| Object
% Read the first 10 records.

dbds.ReadSize = 10;

read(dbds)

%%
% Read the |DatabaseDatastore| object two more times by using the counter
% |n|. Read 10 records at a time.

n = 0;

while(hasdata(dbds) && n~=2)
     read(dbds)
     n = n+1;
end

%% Reset |DatabaseDatastore| Object
% Reset the |DatabaseDatastore| object to the state where no data has been
% read from it. Resetting allows re-reading from the same
% |DatabaseDatastore| object.

reset(dbds)

%% Read Every Record in |DatabaseDatastore| Object
% Read every record in the |DatabaseDatastore| object in increments of
% 50,000 records at a time.
dbds.ReadSize = 50000;
data = readall(dbds);

%%
% Display the first three records of the full data set.
data(1:3,:)

%% Close |DatabaseDatastore| Object and Database Connection

close(dbds)