database.fetch

Execute SQL statement to import data into MATLAB workspace

Syntax

results = fetch(conn,sqlquery)
results = fetch(conn,sqlquery,fetchbatchsize)

Description

results = fetch(conn,sqlquery) executes the SQL statement sqlquery, imports data for the open connection object conn, and returns the data to results. (For details about SQL statements, see exec.)

results = fetch(conn,sqlquery,fetchbatchsize) imports fetchbatchsize rows of data at a time.

Input Arguments

conn

A database connection object.

sqlquery

An SQL statement.

fetchbatchsize

Specifies the number of rows of data to import at a time. Use fetchbatchsize when importing large amounts of data. Retrieving data in increments, as specified by fetchbatchsize, helps reduce overall retrieval time. If fetchbatchsize is not provided, a default value of FetchBatchSize is used. FetchBatchSize is set using setdbprefs.

Output Arguments

results

A cell array, table, dataset array, structure, or numeric matrix depending on specifications set by setdbprefs.

Examples

expand all

Import Data

Import the productDescription column from the productTable table in the dbtoolboxdemo database.

conn = database('dbtoolboxdemo','','');
setdbprefs('DataReturnFormat','cellarray')
results = fetch(conn,'select productdescription from producttable')
results = 

    'Victorian Doll'
    'Train Set'
    'Engine Kit'
    'Painting Set'
    'Space Cruiser'
    'Building Blocks'
    'Tin Soldier'
    'Sail Boat'
    'Slinky'
    'Teddy Bear'

If you experience speed and memory issues, use the fetchbatchsize argument.

View the size of the cell array into which the results were returned.

size(results)
ans =

    10     1

Import Two Columns of Data and View Information About the Data

Import the InvoiceNumber and Paid columns from the Invoice table in the dbtoolboxdemo database.

conn = database('dbtoolboxdemo','','');
setdbprefs('DataReturnFormat','cellarray')
results = fetch(conn,['select InvoiceNumber, '...
'Paid from Invoice']);

View the size of the cell array into which the results were returned.

size(results)
ans =

    12     2

View the results for the first row of data.

results(1,:)
ans = 

    [2101]    [0]

View the data type of the second element in the first row of data.

class(results{1,2})
ans =

logical

More About

expand all

Tips

  • You call the database.fetch function with fetch rather than database.fetch. You implicitly call database.fetch by passing a database object, conn, to fetch. The fetch function also works with a cursor object. See cursor.fetch.

  • The order of records in your database does not remain constant. Use the SQL ORDER BY command in your sqlquery statement to sort data.

Was this topic helpful?