| Database Toolbox User's Guide | Search  Help Desk |
Importing Data into MATLAB from a Database
In this part of the tutorial, you connect to and import data from a database. Specifically, you connect to theSampleDB data source and then import country data from the customers table in the Northwind sample database. You use these Database Toolbox commands:
If you want to see or copy the commands for this part of the tutorial, or if you want to run the set of commands, use the M-file matlab\toolbox\database\dbdemos\dbimportdemo.m.
.SampleDB, is used for the tutorial. SampleDB uses Northwind, a
sample database distributed with Microsoft Access.
.logintimeout(5)
ans=
5
logintimeout in Chapter 4.
database command in the next step to connect to the
database, MATLAB tries to make the connection. If it cannot connect in five
seconds, it stops trying.
.connA = database('SampleDB', '', '')
connA, to be the returned
connection structure. This connection stays open until you close it with the
close command.
database command, you provide the name of the database, which is
the data source SampleDB for this example. The other two arguments for the
database command are username and password. For this example, they are
empty strings because the SampleDB database does not require a user name
or password.
database reference pages.
.ping(connA)
Database Product Name : ACCESS Database Product Version : 3.0 JDBC Driver Name : JDBC-ODBC Bridge (odbcjt32.dll) JDBC Driver Version : 1.1001 (3.40.2829) Max. Database Connections : 64 Current User Name : admin Database URL : jdbc:odbc:SampleDB Auto Commit Transactions : True
.cursorA = exec(connA, 'select country from customers')
cursorA to the returned cursor structure.
exec command, connA is the name of the connection structure. The
second argument, select country from customers, is a valid SQL
statement that selects the country column of data from the customers table.
.cursorA = fetch(cursorA, 10)
fetch is the command that imports data. It has the following two arguments
in this example:
cursorA, the cursor structure returned by exec.
10, the maximum number of rows you want to be returned by fetch. The rowlimit argument is optional and if not included, MATLAB imports all remaining rows.
fetch reassigns the variable cursorA to the cursor
structure containing the rows of data returned by fetch.
.data element in the cell array for cursorA - type:
AA = cursorA.data
AA =
'Germany'
'Mexico'
'Mexico'
'UK'
'Sweden'
'Germany'
'France'
'Spain'
'France'
'Canada'
cursorA cell array contains an element, data, that points to the rows of
data in the array. Here you assign the variable AA to the data element,
cursorA.data.
.close(cursorA) close(connA)