User`s guide

Import Data Using a DatabaseDatastore
6-81
Import Data Using a DatabaseDatastore
This example shows how to import data into MATLAB using a DatabaseDatastore.
You can use a DatabaseDatastore to access collections of data stored in a relational
database. After creating a DatabaseDatastore object, you can preview data, read data
in chunks, and read every record in the data set.
After importing data from a DatabaseDatastore object, you can run calculations on
the data using MapReduce. For an example, see “Analyze Large Data Sets in a Database
with MapReduce” on page 6-85. For more MapReduce examples, see Building
Effective Algorithms with MapReduce.
Create the DatabaseDatastore
The default output data type of any datastore is a table. Set the database preference
for the data return format 'DataReturnFormat' to table for consistency across data
types.
setdbprefs('DataReturnFormat','table')
Create a database connection conn using the native ODBC interface. This code assumes
you are connecting to a MySQL database with the data source named MySQL, user name
username, and password pwd. MySQL contains the table named productTable with 15
product records.
conn = database.ODBCConnection('MySQL','username','pwd');
Create a DatabaseDatastore object dbds using the database connection conn and
SQL query sqlquery. This SQL query retrieves all products from the product table
productTable ordered by product number.
sqlquery = 'select * from productTable order by productNumber';
dbds = datastore(conn,sqlquery);
Preview Data in the DatabaseDatastore
Preview the first eight records in the data set returned by executing sqlquery.
preview(dbds)
ans =
productNumber stockNumber supplierNumber unitCost productDescription