Database Toolbox    

Exporting Multiple Records from MATLAB

In this example, multiple records are imported, manipulated in MATLAB, and then exported to a database. Specifically, you import sales figures for all products, by month, into MATLAB. Then you compute the total sales for each month. Finally, you export the monthly totals to a new table.

You use these Database Toolbox functions:

If you want to see or copy the functions for this part of the tutorial, or if you want to run the set of functions, use the M-file matlab\toolbox\database\dbdemos\dbinsert2demo.m.

  1. If you did not already do so, set up the data source dbtoolboxdemo according to the directions in Setting Up a Data Source. This data source uses the tutorial database.
  2. Check the properties of the tutorial database to be sure it is writable, that is, not read-only.
  3. Connect to the database - type

    You define the returned connection object as conn. You do not need a username or password to access the dbtoolboxdemo database.

  1. Specify that any NULL value read from the database will be converted to a 0 in MATLAB by using the setdbprefs command.
  2. Import the sales figures. Specifically, import all data from the salesVolume table. Type
  3. To get a sense of the data you imported, view the column names in the fetched data set - type

    MATLAB returns

  1. To get a sense of what the data is, view the data for January, which is in column 2 - type

    MATLAB returns

  1. Get the size of the cell array containing the fetched data set, assigning the dimensions to m and n. In a later step, you use these values to compute the monthly totals. Type

    MATLAB returns

  1. Compute the monthly totals - type

    where tmp is the sales volume for all products in a given month i, and monthly is the total sales volume of all products for the month i. To compute monthly using sum, first convert tmp from a cell array to a numeric array using [tmp{:}] because sum will only work on numeric arrays.

    For example, when i is 2, row 1 of monthly is the total of all rows in column 2 of curs.Data, where column 2 is the sales volume for January.

    To see the result, type

    MATLAB returns

  1. To export the column of data, you must first convert it to a cell array - type

    num2cell takes the data in monthly and assigns each row to a row in a new cell array, exdata, which you will export in a later step.

  1. Create a string array containing the column names into which you are inserting the data. In a later step, we will insert the data into the salesTotal column of the yearlySales table; here we assign the variable colnames to the array. Type
  2. Insert the data into the yearlySales table - type
  3. View the yearlySales table in the tutorial database to be sure the data was imported correctly.

  4. Close the cursor and database connection. Type

 Exporting Data from MATLAB, Replacing Existing Data in a Database Accessing Metadata