375
Database Toolbox™ User’s Guide R2013b

Database Toolbox™ II

Embed Size (px)

DESCRIPTION

sf

Citation preview

Page 1: Database Toolbox™ II

Database Toolbox™

User’s Guide

R2013b

Page 2: Database Toolbox™ II

How to Contact MathWorks

www.mathworks.com Webcomp.soft-sys.matlab Newsgroupwww.mathworks.com/contact_TS.html Technical Support

[email protected] Product enhancement [email protected] Bug [email protected] Documentation error [email protected] Order status, license renewals, [email protected] Sales, pricing, and general information

508-647-7000 (Phone)

508-647-7001 (Fax)

The MathWorks, Inc.3 Apple Hill DriveNatick, MA 01760-2098For contact information about worldwide offices, see the MathWorks Web site.

Database Toolbox™ User’s Guide

© COPYRIGHT 1998–2013 by The MathWorks, Inc.The software described in this document is furnished under a license agreement. The software may be usedor copied only under the terms of the license agreement. No part of this manual may be photocopied orreproduced in any form without prior written consent from The MathWorks, Inc.

FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentationby, for, or through the federal government of the United States. By accepting delivery of the Programor Documentation, the government hereby agrees that this software or documentation qualifies ascommercial computer software or commercial computer software documentation as such terms are usedor defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms andconditions of this Agreement and only those rights specified in this Agreement, shall pertain to and governthe use, modification, reproduction, release, performance, display, and disclosure of the Program andDocumentation by the federal government (or other entity acquiring for or through the federal government)and shall supersede any conflicting contractual terms or conditions. If this License fails to meet thegovernment’s needs or is inconsistent in any respect with federal procurement law, the government agreesto return the Program and Documentation, unused, to The MathWorks, Inc.

Trademarks

MATLAB and Simulink are registered trademarks of The MathWorks, Inc. Seewww.mathworks.com/trademarks for a list of additional trademarks. Other product or brandnames may be trademarks or registered trademarks of their respective holders.

Patents

MathWorks products are protected by one or more U.S. patents. Please seewww.mathworks.com/patents for more information.

Page 3: Database Toolbox™ II

Revision HistoryMay 1998 Online Only New for Version 1 for MATLAB® 5.2July 1998 First Printing For Version 1Online only June 1999 Revised for Version 2 (Release 11)December 1999 Second printing For Version 2 (Release 11)Online only September 2000 Revised for Version 2.1 (Release 12)June 2001 Third printing Revised for Version 2.2 (Release 12.1)July 2002 Online only Revised for Version 2.2.1 (Release 13)November 2002 Fourth printing Version 2.2.1June 2004 Fifth printing Revised for Version 3.0 (Release 14)October 2004 Online only Revised for Version 3.1 (Release 14SP1)March 2005 Online only Revised for Version 3.0.2 (Release 14SP2)September 2005 Online only Revised for Version 3.1 (Release 14SP3)March 2006 Online only Revised for Version 3.1.1 (Release 2006a)September 2006 Online only Revised for Version 3.2 (Release 2006b)October 2006 Sixth printing Revised for Version 3.2 (Release 2006b)March 2007 Online only Revised for Version 3.3 (Release 2007a)September 2007 Seventh printing Revised for Version 3.4 (Release 2007b)March 2008 Online only Revised for Version 3.4.1 (Release 2008a)October 2008 Online only Revised for Version 3.5 (Release 2008b)March 2009 Online only Revised for Version 3.5.1 (Release 2009a)September 2009 Online only Revised for Version 3.6 (Release 2009b)March 2010 Online only Revised for Version 3.7 (Release 2010a)September 2010 Online only Revised for Version 3.8 (Release 2010b)reApril 2011 Online only Revised for Version 3.9 (Release 2011a)September 2011 Online only Revised for Version 3.10 (Release 2011b)March 2012 Online only Revised for Version 3.11 (Release 2012a)September 2012 Online only Revised for Version 4.0 (Release 2012b)March 2013 Online only Revised for Version 4.1 (Release 2013a)September 2013 Online only Revised for Version 5.0 (Release 2013b)

Page 4: Database Toolbox™ II
Page 5: Database Toolbox™ II

Contents

Before You Begin

1Working with Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2Connecting to Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2Platform Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2Database Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2Driver Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3Structured Query Language (SQL) . . . . . . . . . . . . . . . . . . . 1-4

Data Type Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

Data Retrieval Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . 1-7Spaces in Table Names or Column Names . . . . . . . . . . . . . 1-7Quotation Marks in Table Names or Column Names . . . . . 1-7Reserved Words in Column Names . . . . . . . . . . . . . . . . . . . 1-7

Working with Data Sources

2Setting Up ODBC Data Sources . . . . . . . . . . . . . . . . . . . . . 2-2

Setting Up JDBC Data Sources . . . . . . . . . . . . . . . . . . . . . 2-3

Accessing Existing JDBC Data Sources . . . . . . . . . . . . . . 2-4

Modifying Existing JDBC Data Sources . . . . . . . . . . . . . . 2-5

Removing JDBC Data Sources . . . . . . . . . . . . . . . . . . . . . . 2-6

Troubleshooting JDBC Driver Problems . . . . . . . . . . . . . 2-7

v

Page 6: Database Toolbox™ II

Database Connection Error Messages . . . . . . . . . . . . . . . 2-8

Database Explorer Error Messages . . . . . . . . . . . . . . . . . . 2-10

Using the Native ODBC Database Connection . . . . . . . . 2-12About the Native ODBC Interface . . . . . . . . . . . . . . . . . . . . 2-12Native ODBC Interface Workflow . . . . . . . . . . . . . . . . . . . . 2-12Native ODBC, ODBC/JDBC Bridge and JDBC InterfaceComparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15

Compatibility and Limitations . . . . . . . . . . . . . . . . . . . . . . . 2-17

Using Visual Query Builder

3Getting Started with Visual Query Builder . . . . . . . . . . . 3-2What Is Visual Query Builder? . . . . . . . . . . . . . . . . . . . . . . 3-2Using Queries to Import Data . . . . . . . . . . . . . . . . . . . . . . . 3-2Using Queries to Export Data . . . . . . . . . . . . . . . . . . . . . . . 3-4

Working with Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6Specifying Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6

Preference Settings for Large Data Import . . . . . . . . . . . 3-10Will All Data (Size n) Fit in a MATLAB Variable? . . . . . . . 3-11Will All of This Data Fit in the JVM Heap? . . . . . . . . . . . . 3-12How Do I Perform Batching? . . . . . . . . . . . . . . . . . . . . . . . . 3-12

Displaying Query Results . . . . . . . . . . . . . . . . . . . . . . . . . . 3-15How to Display Query Results . . . . . . . . . . . . . . . . . . . . . . . 3-15Displaying Data Relationally . . . . . . . . . . . . . . . . . . . . . . . . 3-15Charting Query Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19Displaying Query Results in an HTML Report . . . . . . . . . . 3-21Displaying Query Results with MATLAB ReportGenerator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-22

Fine-Tuning Queries Using Advanced QueryOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-27

vi Contents

Page 7: Database Toolbox™ II

Retrieving All Occurrences vs. Unique Occurrences ofData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-27

Retrieving Data That Meets Specified Criteria . . . . . . . . . . 3-29Grouping Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-32Displaying Results in a Specified Order . . . . . . . . . . . . . . . 3-36Using Having Clauses to Refine Group by Results . . . . . . . 3-39Creating Subqueries for Values from Multiple Tables . . . . 3-42Creating Queries That Include Results from MultipleTables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-47

Additional Advanced Query Options . . . . . . . . . . . . . . . . . . 3-50

Retrieving BINARY and OTHER Data Types . . . . . . . . . 3-51

Importing and Exporting BOOLEAN Data . . . . . . . . . . . 3-54Importing BOOLEAN Data from Databases . . . . . . . . . . . . 3-54Exporting BOOLEAN Data to Databases . . . . . . . . . . . . . . 3-57

Saving Queries in Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-59About Generated Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-59VQB Query Elements in Generated Files . . . . . . . . . . . . . . 3-60

Using Database Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-61About Database Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-61Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-62Configure Your Environment . . . . . . . . . . . . . . . . . . . . . . . . 3-62Database Connection Error Messages . . . . . . . . . . . . . . . . . 3-74Set Database Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-76Display Data from a Single Database Table . . . . . . . . . . . . 3-78Join Data from Multiple Database Tables . . . . . . . . . . . . . . 3-80Define Query Criteria to Refine Results . . . . . . . . . . . . . . . 3-85Query Rules Using the SQL Criteria Panel . . . . . . . . . . . . . 3-87Query Example Using a Left Outer Join . . . . . . . . . . . . . . . 3-89Work with Multiple Databases . . . . . . . . . . . . . . . . . . . . . . . 3-98Import Data to the MATLAB Workspace . . . . . . . . . . . . . . 3-98Save Queries as SQL Code . . . . . . . . . . . . . . . . . . . . . . . . . . 3-101Generate MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-102

vii

Page 8: Database Toolbox™ II

Using Database Toolbox Functions

4Getting Started with Database Toolbox Functions . . . . 4-2

Importing Data from Databases . . . . . . . . . . . . . . . . . . . . . 4-3

Viewing Information About Imported Data . . . . . . . . . . 4-5

Exporting Data to New Record in Database . . . . . . . . . . 4-8

Replacing Existing Database Data with ExportedData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12

Exporting Multiple Records from the MATLABWorkspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14

Exporting Data Using the Bulk Insert Command . . . . . 4-18Bulk Insert to Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18Bulk Insert to Microsoft SQL Server 2005 . . . . . . . . . . . . . 4-20Bulk Insert to MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-22

Retrieving Image Data Types . . . . . . . . . . . . . . . . . . . . . . . 4-25

Working with Database Metadata . . . . . . . . . . . . . . . . . . . 4-27Accessing Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-27Resultset Metadata Objects . . . . . . . . . . . . . . . . . . . . . . . . . 4-33

Using Driver Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-34

About Database Toolbox Objects and Methods . . . . . . . 4-36

Using the exec Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39About the exec Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39Using Cursor Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39Working with Microsoft Excel . . . . . . . . . . . . . . . . . . . . . . . 4-40Database Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-40

viii Contents

Page 9: Database Toolbox™ II

Using the fetch Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42About the fetch Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42fetch Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42Using fetch with a Cursor Object . . . . . . . . . . . . . . . . . . . . . 4-43Database Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-44

Functions — Alphabetical List

5

Index

ix

Page 10: Database Toolbox™ II

x Contents

Page 11: Database Toolbox™ II

1

Before You Begin

• “Working with Databases” on page 1-2

• “Data Type Support” on page 1-5

• “Data Retrieval Restrictions” on page 1-7

Page 12: Database Toolbox™ II

1 Before You Begin

Working with Databases

In this section...

“Connecting to Databases” on page 1-2

“Platform Support” on page 1-2

“Database Support” on page 1-2

“Driver Support” on page 1-3

“Structured Query Language (SQL)” on page 1-4

Connecting to DatabasesBefore you can use this toolbox to connect to a database, you must set up datasources. For more information, see “Configuring Your Environment”.

Platform SupportThis toolbox runs on all platforms that the MATLAB® software supports.

For more information, see Database Toolbox™ system requirements athttp://www.mathworks.com/products/database/requirements.html.

Note This toolbox does not support running MATLAB software sessions withthe -nojvm startup option enabled on UNIX® platforms. (UNIX is a registeredtrademark of The Open Group in the United States and other countries.)

Database SupportThis toolbox supports importing and exporting data from any ODBC- and/orJDBC-compliant database management system, including:

1-2

Page 13: Database Toolbox™ II

Working with Databases

• IBM DB2®

• IBM® Informix®

• Ingres®

• Microsoft® Access™

• Microsoft Excel®

• Microsoft SQL Server®

• MySQL®

• Oracle®

• PostgreSQL (Postgres)

• Sybase® SQL Anywhere®

• Sybase SQL Server®

If you are upgrading an earlier version of a database, you need not doanything special for this toolbox. Simply configure the data sources for thenew version of the database application as you did for the original version.

Driver SupportThis toolbox requires a database driver. Typically, you install a driver whenyou install a database. For instructions about how to install a databasedriver, consult your database administrator.

On Microsoft Windows® platforms, the toolbox supports Open DatabaseConnectivity (ODBC) drivers and Oracle Java® Database Connectivity(JDBC) drivers.

1-3

Page 14: Database Toolbox™ II

1 Before You Begin

Note If you receive this message:

Invalid string or buffer length.

you might be using the wrong driver.

The JDBC-ODBC bridge is known to have issues with 64-bit databasesystems. Use a JDBC driver or the native ODBC interface to connect tothese databases.

On UNIX platforms, the toolbox supports Java DatabaseConnectivity (JDBC) drivers. If your database does not ship withJDBC drivers, download drivers from the Oracle JDBC Web site athttp://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-0

Structured Query Language (SQL)This toolbox supports American National Standards Institute (ANSI®)standard SQL commands.

1-4

Page 15: Database Toolbox™ II

Data Type Support

Data Type SupportYou can import the following data types into the MATLAB Workspace andexport them back to your database:

• BOOLEAN

• CHAR

• DATE

• DECIMAL

• DOUBLE

• FLOAT

• INTEGER

• LONGCHAR

• NUMERIC

• REAL

• SMALLINT

• TIME

• TIMESTAMP

Note When importing TIMESTAMP data into MATLAB, you might getan incorrect value near the daylight savings time change. Possibleworkarounds are to convert TIMESTAMP data to strings in your SQL query,and then convert them back to your desired type in MATLAB, or try usinga different driver for your database.

• TINYINT

1-5

Page 16: Database Toolbox™ II

1 Before You Begin

Note Database Toolbox interprets the TINYINT data type as BOOLEAN andimports it into the MATLAB workspace as logical true (1) or false (0).For more information about how Database Toolbox handles BOOLEAN data,see “Importing and Exporting BOOLEAN Data” on page 3-54.

• VARCHAR

• NTEXT

You can import data of types not included in this list into the MATLABWorkspace. However, you might need to manipulate such data before youcan process it in MATLAB.

Note Data types LONGCHAR and NTEXT are not supported for the native ODBCinterface.

1-6

Page 17: Database Toolbox™ II

Data Retrieval Restrictions

Data Retrieval Restrictions

In this section...

“Spaces in Table Names or Column Names” on page 1-7

“Quotation Marks in Table Names or Column Names” on page 1-7

“Reserved Words in Column Names” on page 1-7

Spaces in Table Names or Column NamesMicrosoft Access supports the use of spaces in table and column names, butmost other databases do not. Queries that retrieve data from tables and fieldswhose names contain spaces require delimiters around table names and fieldnames. In Access, enclose the table names or field names in quotation marks,for example, "order id". Other databases use different delimiters, such asbrackets, [ ]. In Visual Query Builder, table names and field names thatinclude spaces appear in quotation marks.

Quotation Marks in Table Names or Column NamesDo not include quotation marks in table names or column names. TheDatabase Toolbox software does not support data retrieval from table andcolumn names that contain quotation marks.

Reserved Words in Column NamesYou cannot use the Database Toolbox software to import or export data incolumns whose names contain database reserved words, such as DATE orTABLE.

1-7

Page 18: Database Toolbox™ II

1 Before You Begin

1-8

Page 19: Database Toolbox™ II

2

Working with Data Sources

• “Setting Up ODBC Data Sources” on page 2-2

• “Setting Up JDBC Data Sources” on page 2-3

• “Accessing Existing JDBC Data Sources” on page 2-4

• “Modifying Existing JDBC Data Sources” on page 2-5

• “Removing JDBC Data Sources” on page 2-6

• “Troubleshooting JDBC Driver Problems” on page 2-7

• “Database Connection Error Messages” on page 2-8

• “Database Explorer Error Messages” on page 2-10

• “Using the Native ODBC Database Connection” on page 2-12

Page 20: Database Toolbox™ II

2 Working with Data Sources

Setting Up ODBC Data SourcesFor instructions on setting up ODBC data sources, see “Configure ODBCData Sources”.

2-2

Page 21: Database Toolbox™ II

Setting Up JDBC Data Sources

Setting Up JDBC Data SourcesFor instructions on setting up JDBC data sources, see “Configure JDBC DataSources”.

2-3

Page 22: Database Toolbox™ II

2 Working with Data Sources

Accessing Existing JDBC Data SourcesTo access an existing data source from Visual Query Builder in futureMATLAB sessions:

1 In Visual Query Builder, select Query > Define JDBC data source.

2 In the Define JDBC data sources dialog box, click Use Existing File.

3 In the Specify Existing JDBC data source MAT-file dialog box, select theMAT-file that contains the data sources you want to use and click Open.

The data sources in the selected MAT-file appear in the Define JDBC datasources dialog box.

4 Click OK to close the Define JDBC data sources dialog box. The datasources now appear in the Visual Query Builder Data source list.

2-4

Page 23: Database Toolbox™ II

Modifying Existing JDBC Data Sources

Modifying Existing JDBC Data Sources1 Access the existing data source as described in “Accessing Existing JDBCData Sources” on page 2-4.

2 Select the data source in the Define JDBC Data Sources dialog box.

3 Modify the data in the Driver and URL fields.

4 Click Add/Update.

5 Click OK to save your changes and close the Define JDBC data sourcesdialog box.

2-5

Page 24: Database Toolbox™ II

2 Working with Data Sources

Removing JDBC Data Sources1 Access the existing data source as described in “Accessing Existing JDBCData Sources” on page 2-4.

2 Click Remove.

3 Click OK to save your changes and close the Define JDBC data sourcesdialog box.

2-6

Page 25: Database Toolbox™ II

Troubleshooting JDBC Driver Problems

Troubleshooting JDBC Driver ProblemsThis section describes how to address common data source access problems,in which selecting a data source in the Visual Query Builder list producesan error, or the data source is not in the list as expected. There are severalpotential causes for these issues:

• The database is unavailable, or there are connectivity problems. Tryselecting the data source in VQB again. If you are still unable to access thedata source, contact your database administrator.

• You ran the clear all command in the MATLAB Command Window afteryou defined a JDBC data source. In this case, redefine the data source byfollowing the instructions in “Configure JDBC Data Sources”.

2-7

Page 26: Database Toolbox™ II

2 Working with Data Sources

Database Connection Error MessagesConnection Error Messages and Probable Causes

Vendor Error Message Probable Causes

All Unable to find JDBC driver. • Path to the JDBC driver jar file isnot on the static or dynamic classpath.

• Incorrect driver name providedwhile using the 'driver' and'url' syntax.

All [Microsoft][ODBC Driver Manager]The specified DSN contains anarchitecture mismatch between Driverand Application

You tried to open a 32-bit applicationwhen running MATLAB in 64-bitmode. Restart MATLAB to run in32-bit mode using the commandmatlab win32.

Microsoft SQLServer

The TCP/IP connection to the hosthostname, port portnumber has failed.Error: “null. Verify the connectionproperties, check that an instance ofSQL Server is running on the host andaccepting TCP/IP connections at theport, and that no firewall is blockingTCP connections to the port.”

Incorrect server name or portnumber. Microsoft SQL Serveruses a dynamic port for JDBC andthe value should be verified usingMicrosoft SQL Server ConfigurationManager.

Microsoft SQLServer

This driver is not configured forintegrated authentication.

The Microsoft SQL Server Windowsauthentication library is not addedto librarypath.txt. For moreinformation, see the databaseexample for Microsoft SQL ServerAuthenticated Database Connection.

2-8

Page 27: Database Toolbox™ II

Database Connection Error Messages

Connection Error Messages and Probable Causes (Continued)

Vendor Error Message Probable Causes

Microsoft SQLServer

Invalid string or buffer length. 64-bit ODBC driver error. Use aJDBC driver or the native ODBCinterface instead.

MySQL Access denied for user'user'@'machinename' (usingpassword: YES)

Incorrect user name and passwordcombination.

MySQL Communications link failure.The last packet sent successfully tothe server was 0 milliseconds ago. Thedriver has not received any packetsfrom the server.

Incorrect server name or portnumber.

MySQL Unknown database 'databasename'. Provided database name is incorrect.

Oracle Error when connecting to Oracle oci8database using JDBC driver:

Error using com.mathworks.toolbox.database.databaseConnect/makeDatabaseConnection

Java exception occurred:

java.lang.UnsatisfiedLinkError: no ocijdbc11 in

java.library.pathat

java.lang.ClassLoader.loadLibrary(Unknown Source)at

java.lang.Runtime.loadLibrary0.......

MATLAB cannot find the OracleDLL that the oci8 drivers need. Tocorrect the problem, add the path forthe location of the Oracle DLLs to$MATLAB/toolbox/local/librarypath.txt.

Oracle Invalid Oracle URL specified:

OracleDataSource.makeURL

DriverType parameter is notspecified.

Oracle The Network Adapter could notestablish the connection.

Either Server or Portnumber is notspecified or has an incorrect value.

See Also database

2-9

Page 28: Database Toolbox™ II

2 Working with Data Sources

Database Explorer Error MessagesDatabase Explorer Error Messages and Probable Causes

Vendor Position ofError

Error Message Probable Causes

All Error occursin theConnectionFailuredialogbox afterclickingConnectin theConnectto a datasourcedialog box.

[Microsoft][ODBC DriverManager] Data source namenot found and no default driverspecified

JDBC data sources created byVisual Query Builder cannotbe used in Database Explorer.You must run the followingcommand: setdbprefs(...'JDBCDataSourceFile','')and then create a new JDBCdata source from DatabaseExplorer.

All Error occursin theConnectto a datasourcedialog box.

[Microsoft][ODBC DriverManager] The specified DSNcontains an architecturemismatch between Driverand Application

You tried to open a 32-bitapplication when runningMATLAB in 64-bit mode.Restart MATLAB to runin 32-bit mode using thecommand matlab win32.

MicrosoftAccess

Error occursin theConnectionFailuredialogbox afterclickingConnectin theConnectto a datasourcedialog box.

[Microsoft][ODBC MicrosoftAccess Driver] ‘(unknown)’ is nota valid path. make sure that thepath name is spelled correctlyand that you are connected to theserver on which the file resides

The file location of theMicrosoft Access database isincorrect. Verify the locationof the database file and modifythe existing file location byselecting New > ODBC andselecting the existing databasename from ODBC DataSource Administrator dialogbox. Then select Configureto change the database filelocation.

2-10

Page 29: Database Toolbox™ II

Database Explorer Error Messages

Database Explorer Error Messages and Probable Causes (Continued)

Vendor Position ofError

Error Message Probable Causes

MicrosoftSQL Server

Error occursIn the DataPreviewErrordialogbox afterselecting acolumn of atable in theDatabaseBrowserpane.

Invalid Object Name catalogname.table name

You must select theappropriate schema namein Database Explorer using theCatalog/Schema address barabove the table columns tree.

Oracle Error occursinside theDatabaseBrowserpane.

No tables found in this schemaConsider changing the schema.

This error occurs when usingthe Oracle ODBC driverbecause of a problem inthe JDBC-ODBC bridge.Please switch your databaseconnection to use a JDBCdriver. For more information,see “Configure JDBC DataSources”.

2-11

Page 30: Database Toolbox™ II

2 Working with Data Sources

Using the Native ODBC Database Connection

In this section...

“About the Native ODBC Interface” on page 2-12

“Native ODBC Interface Workflow” on page 2-12

“Native ODBC, ODBC/JDBC Bridge and JDBC Interface Comparison” onpage 2-15

“Compatibility and Limitations” on page 2-17

About the Native ODBC InterfaceThe native ODBC interface is a C++ library that allows direct communicationwith the ODBC driver instead of using the Oracle JDBC/ODBC bridge. Thiseliminates issues from using the bridge and eliminates heap memory outagescaused by the JVM™ heap memory restrictions. Using the native ODBCinterface results in an improved data import and export experience, especiallywhen working with large amounts of data.

Native ODBC Interface WorkflowThis example shows how to connect to a database using the native ODBCinterface, execute an SQL statement and fetch the returned data, insert data,and then close the connection.

Connect to the Database Using the Native ODBC Interface

Connect to the database with the ODBC data source name, dbtoolboxdemo,using the user name, admin, and password, admin.

conn = database.ODBCConnection('dbtoolboxdemo','admin','admin');

database.ODBCConnection returns conn as a database.ODBCConnectionobject.

Import Data Using the Native ODBC Interface

2-12

Page 31: Database Toolbox™ II

Using the Native ODBC Database Connection

Select data in column productDescription from productTable using thedatabase connection, conn. Assign the returned cursor object to the variablecurs.

curs = exec(conn,'select productDescription from productTable');

With the native ODBC interface, exec returns curs as an ODBCCursorObject instead of a Database Cursor Object.

Note The native ODBC interface has a default batch size of 100,000 thatenables acceptable performance. To override this value, you must usesetdbprefs as follows. Set FetchInBatches to yes and set FetchBatchSizeto a specific batch size number <h>.

setdbprefs('FetchInBatches','yes')setdbprefs('FetchBatchSize','<h>')

Use fetch to import all data into the cursor object curs, and store the data ina cell array contained in the cursor object field curs.Data.

curs = fetch(curs);

View the contents of the Data element in the cursor object curs.

curs.Data

ans =

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

2-13

Page 32: Database Toolbox™ II

2 Working with Data Sources

Export Data Using the Native ODBC Interface

Define the columns of data to insert in the cell array colnames.

colnames = {'productNumber','stockNumber','supplierNumber',...'unitCost','productDescription'}

colnames =

Columns 1 through 3

'productNumber' 'stockNumber' 'supplierNumber'

Columns 4 through 5

'unitCost' 'productDescription'

Define the data for the row to insert in the cell array coldata.

coldata = {11,800999,1006,9.00,'Toy Car'}

coldata =

[11] [800999] [1006] [9] 'Toy Car'

Insert the data in coldata into the productTable with the defined columnnames, colnames.

insert(conn,'productTable',colnames,coldata);

Caution: The Microsoft Access ODBC driver demonstrates unexpectedbehavior during large inserts. When inserting large amounts of data withMicrosoft Access, insert the data in batches. For example, if you want toinsert 100,000 rows of data, insert 10,000 rows at a time.

Close the cursor object, curs, and then close the database connection, conn.

close(curs);close(conn);

2-14

Page 33: Database Toolbox™ II

Using the Native ODBC Database Connection

Caution: Leaving cursor and connection objects open or overwriting openobjects can result in unexpected behavior. Once you are finished working withthese objects, you must close them using close.

Native ODBC, ODBC/JDBC Bridge and JDBC InterfaceComparisonThis table highlights the differences between using the native ODBC,ODBC/JDBC bridge, and JDBC interfaces to access and manipulate data ina database.

Item Native ODBC ODBC/JDBCBridge

JDBC

Connectionfunction

Usedatabase.ODBCConnection

Use database Use database

Actions Can perform thefollowing actions:

• Query data(exec)

• Import data(fetch)

• Run storedprocedure(exec)

• Export data(insert,fastinsert)

• Closeconnection(close)

Can perform thefollowing actions:

• Query data(exec)

• Import data(fetch)

• Export data(insert,fastinsert,datainsert,update)

• Run storedprocedure(exec,runstoredprocedure)

• Retrievemetadata(dmd, tables,columns,

Can perform thefollowing actions:

• Query data(exec)

• Import data(fetch)

• Export data(insert,fastinsert,datainsert,update)

• Run storedprocedure(exec,runstoredprocedure)

• Retrievemetadata(dmd, tables,columns,

2-15

Page 34: Database Toolbox™ II

2 Working with Data Sources

Item Native ODBC ODBC/JDBCBridge

JDBC

database.catalogs,and manyothers)

• Use DatabaseExplorer(dexplore)

• Closeconnection(close)

database.catalogs,and manyothers)

• Use DatabaseExplorer(dexplore)

• Closeconnection(close)

Underlyingtechnology

C++ Java Java

Memoryperformance

Restrictedby MATLABmemory, butnot JVM heapmemory

Restricted byboth JVMheap memoryand MATLABmemory

Restricted byboth JVMheap memoryand MATLABmemory

Data accessperformance

Fastest Slowest Medium

64-bit systems No major issues Several knownissues withconnectivity anddata access

No major issues

Data typesupport

Long data typesare not supported(e.g. LONG, BLOB,etc.)

Long data typesare supported

Long data typesare supported

Note For more information about the database.ODBCConnection syntax,see the native ODBC interface example in database.

2-16

Page 35: Database Toolbox™ II

Using the Native ODBC Database Connection

Compatibility and LimitationsThe native ODBC interface has the following compatibility and limitationconsiderations:

• Native ODBC database connections are supported on MATLAB 32-bit and64-bit versions using the database function. The native ODBC interfacesupports 64-bit database vendors. This interface is backward compatiblefor 32-bit versions. The bitness of MATLAB must always match the bitnessof the database driver.

• The native ODBC interface is available only for the command line. Youcannot use Database Explorer to access the native ODBC interface.

• The native ODBC interface does not support long data types such as OracleLONG and SQL Server NTEXT. If you get one of the following errors, you areaccessing an unsupported data type:

- Driver unable to retrieve length for column number: <indexof column in the query>

- Out of memory. Type HELP MEMORY for your options.

Concepts • “Using the exec Function” on page 4-39• “Using the fetch Function” on page 4-42

2-17

Page 36: Database Toolbox™ II

2 Working with Data Sources

2-18

Page 37: Database Toolbox™ II

3

Using Visual Query Builder

• “Getting Started with Visual Query Builder” on page 3-2

• “Working with Preferences” on page 3-6

• “Preference Settings for Large Data Import” on page 3-10

• “Displaying Query Results” on page 3-15

• “Fine-Tuning Queries Using Advanced Query Options” on page 3-27

• “Retrieving BINARY and OTHER Data Types” on page 3-51

• “Importing and Exporting BOOLEAN Data” on page 3-54

• “Saving Queries in Files” on page 3-59

• “Using Database Explorer” on page 3-61

Page 38: Database Toolbox™ II

3 Using Visual Query Builder

Getting Started with Visual Query Builder

In this section...

“What Is Visual Query Builder?” on page 3-2

“Using Queries to Import Data” on page 3-2

“Using Queries to Export Data” on page 3-4

What Is Visual Query Builder?Visual Query Builder (VQB) is an easy-to-use graphical user interface (GUI)for exchanging data with your database. To start VQB, use querybuilder.You can use VQB to:

• Build queries to retrieve data by selecting information from lists instead ofusing MATLAB functions.

• Store data retrieved from a database in a MATLAB cell array, structure, ornumeric matrix.

• Process the retrieved data using the MATLAB suite of functions.

• Display retrieved information in relational tables, reports, and charts.

• Export data from the MATLAB workspace into new rows in a database.

Using Queries to Import DataThe following steps summarize how to use VQB to import data.

3-2

Page 39: Database Toolbox™ II

Getting Started with Visual Query Builder

�����������

������������

��� ������������ ������������������

���������������

�������������������������� �����������������������

�!��� ���� ������"����

�� #�����$����%��������������������&'()'*'����+�����

, ��� ��������������������������

�- ���� ��� ������������ ��.�������&$������

/ ������������

0 �����1)�����"����

2�'���.��������������������

(�������!�������1����*����� �� ��������������!�&'()'* ��" ��

-������������.����!�"��

3-3

Page 40: Database Toolbox™ II

3 Using Visual Query Builder

For a step-by-step example of how to use queries to import data into theMATLAB workspace from a database, see “Using Queries to Import DatabaseData”.

Using Queries to Export DataThe following steps summarize how to use VQB to export data.

3-4

Page 41: Database Toolbox™ II

Getting Started with Visual Query Builder

�����������

,����������

��� ���������� ������������������

���������������

����������������!��!���3 �������

2 ���� ��� ������������ ��� ��������������3 �����.45))� ��.�������&$������

0 ����&'()'*�����"����

/� � ����������������������.������3 ����

(�������!�������1����*����� �� ��������������!�&'()'* ��" ��

-������������.����!�"��

For a step-by-step example of how to use queries to export data from theMATLAB workspace to a database, see “Using Queries to Export Data toDatabases”.

3-5

Page 42: Database Toolbox™ II

3 Using Visual Query Builder

Working with Preferences

Specifying PreferencesDatabase Toolbox preferences enable you to specify:

• How NULL data in a database is represented after you import it into theMATLAB workspace

• The format of data retrieved from databases

• The method of error notification

• The preference for fetching in batches

1 From Visual Query Builder, select Query > Preferences. The Preferencesdialog box appears. Alternatively, from the MATLAB Toolstrip, clickPreferences and select Database Toolbox.

3-6

Page 43: Database Toolbox™ II

Working with Preferences

3-7

Page 44: Database Toolbox™ II

3 Using Visual Query Builder

2 Specify the Preferences settings as described in the following table.

PreferenceAcceptableValues Description

ReadNULLstrings as:

null (default) Specifies how NULL strings appear after being fetched from adatabase.

ReadNULLnumbersas:

Nan (default) Specifies how NULL numbers appear after being fetched from adatabase. If you accept the default value for this field, NULL dataimported from databases into the MATLAB workspace appearsas NaN. Setting this field to 0 causes NULL data imported into theMATLAB workspace to appear as 0s.

WriteNULLstrings as:

null (default) Specifies how NULL strings appear after being exported to adatabase. This setting does not apply to Database Explorer(dexplore).

WriteNULLnumbersas:

Nan (default) Specifies how NULL numbers appear after being exported to adatabase. This setting does not apply to Database Explorer(dexplore).

Datareturnformat

cell array,numeric,structure, ordataset

Select a data format based on the type of data you are importing,memory considerations, and your preferred method of workingwith retrieved data.

• cellarray (default) — Imports nonnumeric data intoMATLAB cell arrays.

• numeric — Imports data into MATLAB matrix of doubles.Nonnumeric data types are considered NULL and appear asspecified in the Read NULL numbers as: setting. Useonly when data to retrieve is in numeric format, or whennonnumeric data to retrieve is not relevant.

• structure— Imports data into a MATLAB structure. Use forall data types. Facilitates working with returned columns.

• dataset— Imports data into MATLAB dataset objects. Thisoption requires Statistics Toolbox™.

This setting does not apply to Database Explorer (dexplore).If you are using Database Explorer, the data return format is

3-8

Page 45: Database Toolbox™ II

Working with Preferences

PreferenceAcceptableValues Description

specified using Imported Data panel in the Database Explorerinterface.

Errorhandling

store, report,or empty

• Set this field to store or empty to direct errors to either adialog box when using Visual Query Builder or a message fieldwhen using the Database Toolbox command line interface.

• Set this field to report to display query errors in the MATLABCommand Window.

This setting does not apply to Database Explorer (dexplore).

CursorFetch

Fetch InBatches andBatch Size

Specifies if fetch retrieves data in batches with a user-definedBatch Size. The default Batch Size is 1,000. For moreinformation, see “Preference Settings for Large Data Import”on page 3-10.

This setting does not apply to Database Explorer (dexplore).If you are using Database Explorer, the import batch size isspecified using Preferences on the Database Explorer Toolstrip.

3 Click OK. For more information about Preferences, see the setdbprefsfunction reference page.

3-9

Page 46: Database Toolbox™ II

3 Using Visual Query Builder

Preference Settings for Large Data Import

In this section...

“Will All Data (Size n) Fit in a MATLAB Variable?” on page 3-11

“Will All of This Data Fit in the JVM Heap?” on page 3-12

“How Do I Perform Batching?” on page 3-12

When using the setdbprefs to set 'FetchInBatches' and 'FetchBatchSize'or the Cursor Fetch option for the Preference dialog box, use the followingguidelines to determine what batch size value to use. These guidelines arebased on evaluating:

• The size of your data (n rows) to import into MATLAB

• The JVM heap requirements for the imported data

The general logic for making these evaluations are:

• If your data (n rows) will fit in a MATLAB variable, then will all your datafit in the JVM heap?

- If yes, use the following preference setting:

setdbprefs('FetchInBatches','no')

- If no, evaluate h such that h < n and data of size h rows fits in the JVMheap. Use the following preference setting:

setdbprefs('FetchInBatches','yes')setdbprefs('FetchBatchSize','<h>')

• If your data (n rows) will not fit in a MATLAB variable, then:

- Evaluate m such that m < n and the data of size m rows fits in aMATLAB variable.

- Evaluate h such that h < m < n and data of size h rows fits in the JVMheap. Use the following preference setting:

setdbprefs('FetchInBatches','yes')setdbprefs('FetchBatchSize','<h>')

3-10

Page 47: Database Toolbox™ II

Preference Settings for Large Data Import

Then import data using fetch or runsqlscript by using the value 'm'to limit the number of rows in the output:

curs = fetch(curs,<m>)

or

results = runsqlscript(conn,<filename>.sql,'rowInc','<m>')

• If you are using the native ODBC interface to import large amounts ofdata, you do not need to change these settings because the native ODBCinterface always fetches data in batches of 100,000 rows. You can stilloverride the default batch size by setting 'FetchInBatches' to 'yes'and 'FetchBatchSize' to a number of your choice. Note that JVM heapmemory restrictions do not apply in this case since the native ODBCinterface is a C++ API.

Will All Data (Size n) Fit in a MATLAB Variable?This example shows how to estimate the size of data to import from adatabase.

It is important to have an idea of the size of data that you are looking toimport from a database. Finding the size of the table(s) in the database can bemisleading because MATLAB representation of the same data is most likelygoing to consume more memory. For instance, say your table has one numericcolumn and one text column and you are looking to import it in a cell array.Here is how you can estimate the total size.

data = {1001, 'some text here'};whos data

Name Size Bytes Class Attributes

data 1x2 156 cell

If you are looking to import a thousand rows of the table, the approximate sizein MATLAB would be 156 * 1000 = 156 KB. You can replicate this process fora structure or a dataset depending on which data type you want to import thedata in. Once you know the size of data to be imported in MATLAB, you can

3-11

Page 48: Database Toolbox™ II

3 Using Visual Query Builder

determine whether it fits in a MATLAB variable by executing the commandmemory in MATLAB.

A conservative approach is recommended here so as to take into accountmemory consumed by other MATLAB tasks and other processes running onyour machine. For example, even if you have 12 GB RAM and the memorycommand in MATLAB shows 14 GB of longest array possible, it might still bea good idea to limit your imported data to a reasonable 2 or 3 GB to be able toprocess it without issues. Note that these numbers vary from site to site.

Will All of This Data Fit in the JVM Heap?This example shows how to determine the size of the JVM heap.

The value of your JVM heap can be determined by selecting MATLABPreferences and General > Java Heap Memory. You can increase thisvalue to an allowable size, but keep in mind that increasing JVM heap reducesthe total memory available to MATLAB arrays. Instead, consider fetchingdata in small batches to keep a low to medium value for heap memory.

How Do I Perform Batching?There are three different methods based on your evaluations of the data sizeand the JVM heap size. Let n be the total number of rows in the data you arelooking to import, m be the number of rows that fit in a MATLAB variable,and h be the number of rows that fit in the JVM heap.

Method 1 — Data Does Not Fit in MATLAB Variable or JVMHeapIf your data (n) does not fit in a MATLAB variable or a JVM heap, you need tofind h and m such that h < m < n.

To use automated batching to fetch those m rows in MATLAB:

setdbprefs('FetchInBatches','yes')setdbprefs('FetchBatchSize','<h>')

If using exec, fetch, and connection object conn:

3-12

Page 49: Database Toolbox™ II

Preference Settings for Large Data Import

curs = exec(conn,'Select .');curs = fetch(curs,<m>);

If using runsqlscript to run a query from an SQL file:

results = runsqlscript(conn,'<filename>.sql','rowInc','<m>')

Once you are done processing these m rows, you can import the next mrows using the same commands. Keep in mind, however, that using thesame cursor object curs for this results in the first curs being overwritten,including everything in curs.Data.

Note If 'FetchInBatches' is set to 'yes' and the total number of rowsfetched is less than 'FetchBatchSize', MATLAB shows a warning messageand then fetches all the rows. The message is Batch size specified waslarger than the number of rows fetched.

Method 2 — Data Does Fit In MATLAB Variable But Not in JVMHeapIf your data (n) does fit in a MATLAB variable but not in a JVM heap, youneed to find h such that h < n.

To use automated batching to fetch where h rows fit in the JVM heap:

setdbprefs('FetchInBatches','yes')setdbprefs('FetchBatchSize','<h>')

If using exec, fetch, and the connection object conn:

curs = exec(conn,'Select .');curs = fetch(curs);

If using runsqlscript to run a query from an SQL file:

results = runsqlscript(conn,'<filename>.sql')

Note that when you use automated batching and do not supply the rowLimitparameter to fetch or the rowInc parameter to runsqlscript, a count query

3-13

Page 50: Database Toolbox™ II

3 Using Visual Query Builder

is executed internally to get the total number of rows to be imported. This isdone to preallocate the output variable for better performance. In most cases,the count query overhead is not much, but you can easily avoid it if you knowor have a good idea of the value of n:

curs = fetch(curs,<n>)

or

results = runsqlscript(conn,'<filename>.sql','rowInc','<n>')

Method 3 — Data Fits in MATLAB Variable and JVM HeapIf your data (n) fits in a MATLAB variable and also in a JVM heap, then youneed not use batching at all.

setdbprefs('FetchInBatches','no')

If using fetch:

curs = fetch(curs);

If using runsqlscript to run a query from an SQL file:

results = runsqlscript(conn,'<filename>.sql')

3-14

Page 51: Database Toolbox™ II

Displaying Query Results

Displaying Query Results

In this section...

“How to Display Query Results” on page 3-15

“Displaying Data Relationally” on page 3-15

“Charting Query Results” on page 3-19

“Displaying Query Results in an HTML Report” on page 3-21

“Displaying Query Results with MATLAB® Report Generator™” on page3-22

How to Display Query ResultsTo display query results, perform one of the following actions:

• Enter the variable name to which to assign the query results in theMATLAB Command Window.

• Double-click the variable in the VQB Data area to view the data in theVariables editor.

The examples in this section use the saved query basic.qry. To load andconfigure this query:

1 Select Query > Preferences, and set Read NULL numbers as to 0.

2 Select Query > Load.

3 In the Load SQL Statement dialog box, select basic.qry from the Filename field and click Open.

4 In VQB, enter a value for the MATLAB workspace variable, forexample, A, and click Execute.

Displaying Data RelationallyTo display the results of basic.qry:

1 Execute basic.qry.

3-15

Page 52: Database Toolbox™ II

3 Using Visual Query Builder

2 Select Display > Data.

The query results appear in a figure window.

This display shows only unique values for each field, so you should notread each row as a single record. In this example, there are 10 entries forStockNumber, eight entries for January and February, and 10 entriesfor March. The number of entries in each field corresponds to the numberof unique values in the field.

3 Click a value in the figure window, for example, StockNumber 400876,to see its associated values.

3-16

Page 53: Database Toolbox™ II

Displaying Query Results

The data associated with the selected value appears in bold font and isconnected with a dotted line. The data shows that sales for item 400876 are3000 in January, 2400 in February, and 1500 in March.

4 As another example, click 3000 under January. It shows three differentitems with sales of 3000 units in January: 400314, 400876, and 400999.

3-17

Page 54: Database Toolbox™ II

3 Using Visual Query Builder

3-18

Page 55: Database Toolbox™ II

Displaying Query Results

Charting Query ResultsTo chart the results of basic.qry:

1 Select Display > Chart.

The Visual Query Builder Charting dialog box appears.

2 Select a type of chart from the Charts list. In this example, choose a piechart by specifying pie.

A preview of the pie chart, with each stock item displayed in a differentcolor, appears at the bottom of the dialog box.

3-19

Page 56: Database Toolbox™ II

3 Using Visual Query Builder

3 Select the data to display in the chart from the X data, Y data, and Zdata list boxes. In this example, select March from the X data list box todisplay a pie chart of March data.

The pie chart preview now shows percentages for March data.

4 To display a legend, which maps colors to the stock numbers, select theShow legend check box.

The Legend labels field becomes active.

5 Select StockNumber from the Legend labels list box.

A legend appears in the chart preview. Drag and move the legend in thepreview as needed.

3-20

Page 57: Database Toolbox™ II

Displaying Query Results

6 Click Close to close the Charting dialog box.

Displaying Query Results in an HTML ReportTo display results for basic.qry in an HTML report, selectDisplay > Report.

The query results appear as a table in a Web browser. Each row represents arecord from the database. In this example, sales for item 400876 are 3000 inJanuary, 2400 in February, and 1500 in March.

Tip Because some browsers do not start automatically, you may need to openyour Web browser before displaying the query results.

3-21

Page 58: Database Toolbox™ II

3 Using Visual Query Builder

Displaying Query Results with MATLAB ReportGeneratorTo use the MATLAB Report Generator™ software to customize the displayof the results of basic.qry:

1 Select Display > Report Generator.

2 The Report Explorer opens, listing sample report templatesthat you can use to create custom reports. Select the templatematlabroot/toolbox/database/vqb/databasetlbx.rpt from the Optionspane in the middle of the Report Explorer window.

3-22

Page 59: Database Toolbox™ II

Displaying Query Results

3 Open the report template for editing by clicking Open a Report file orstylesheet.

a In the Outline pane on the left, under Report Generator >databasetlbx.rpt, select Table.

b In the Properties pane on the right, do the following:

3-23

Page 60: Database Toolbox™ II

3 Using Visual Query Builder

i In Table Content > Workspace Variable Name, enter the nameof the variable to which you assigned the query results in VQB, forexample, 'A'.

ii Under Header/Footer Options, set Number of header rows to 0.

c Click Apply.

4 Select File > Report to run the report.

The report appears in a Web browser.

5 Field names do not automatically display as column headers in the report.To display the field names:

a Modify the workspace variable A as follows:

3-24

Page 61: Database Toolbox™ II

Displaying Query Results

A = [{'Stock Number', 'January', 'February', 'March'};A]

b In the MATLAB Report Generator Properties pane, change Number ofheader rows to 1 and regenerate the report. The report now displaysfield names as headings.

Each row represents a record from the database. For example, sales foritem 400876 are 3000 in January, 2400 in February, and 1500 in March.

For more information about the MATLAB Report Generator product, click theHelp button in the Report Explorer.

3-25

Page 62: Database Toolbox™ II

3 Using Visual Query Builder

Tip Because some browsers are not configured to launch automatically, youmay need to open your Web browser before displaying the report.

3-26

Page 63: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

Fine-Tuning Queries Using Advanced Query Options

In this section...

“Retrieving All Occurrences vs. Unique Occurrences of Data” on page 3-27

“Retrieving Data That Meets Specified Criteria” on page 3-29

“Grouping Statements” on page 3-32

“Displaying Results in a Specified Order” on page 3-36

“Using Having Clauses to Refine Group by Results” on page 3-39

“Creating Subqueries for Values from Multiple Tables” on page 3-42

“Creating Queries That Include Results from Multiple Tables” on page 3-47

“Additional Advanced Query Options” on page 3-50

Note For more information about advanced query options, select Help inany of the dialog boxes for the options.

Retrieving All Occurrences vs. Unique Occurrencesof DataTo use the dbtoolboxdemo data source to demonstrate how to retrieve allversus distinct occurrences of data:

1 Set the Data return format preference to cellarray.

2 Set Read NULL numbers as to NaN.

3 In Data operation, choose Select.

4 In Data source, select dbtoolboxdemo.

Do not specify Catalog or Schema.

5 In Tables, select SalesVolume.

6 In Fields, select January.

3-27

Page 64: Database Toolbox™ II

3 Using Visual Query Builder

7 To retrieve all occurrences of January:

a In Advanced query options, select All.

b Assign the query results to theMATLAB workspace variable All.

c Click Execute to run the query.

8 To retrieve only unique occurrences of data:

a In Advanced query options, select Distinct.

b Assign the query results to aMATLAB workspace variable Distinct.

c Click Execute to run the query.

9 In the MATLAB Command Window, enter All, Distinct to display thequery results:

3-28

Page 65: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

The value 3000 appears three times in All, but appears only once inDistinct.

Retrieving Data That Meets Specified CriteriaUse basic.qry and theWhere field in Advanced query options to retrievestock numbers greater than 400000 and less than 500000:

1 Load basic.qry.

2 Set the Data return format preference to cellarray.

3 Set Read NULL numbers as to NaN.

4 In Advanced query options, click Where.

The WHERE Clauses dialog box appears.

5 In Fields, select the field whose values you want to restrict, StockNumber.

6 In Condition, specify that StockNumber must be greater than 400000.

a Select Relation.

b In the drop-down list to the right of Relation, select >.

c In the field to the right of the drop-down list, enter 400000.

The WHERE Clauses dialog box now looks as follows.

3-29

Page 66: Database Toolbox™ II

3 Using Visual Query Builder

d Click Apply.

The clause that you defined, StockNumber > 400000, appears in theCurrent clauses area.

3-30

Page 67: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

7 Add the condition that StockNumber must also be less than 500000.

a In Current clauses, select StockNumber > 400000.

b In Current clauses, click Edit or double-click the StockNumber entry.

c For Operator, select AND.

d Click Apply.

The Current clauses field now displays:

StockNumber > 400000 AND

e In Fields, select StockNumber.

f In Condition, select Relation.

g In the drop-down list to the right of Relation, select <.

h In the field to the right of the drop-down list, enter 500000.

i Click Apply.

The Current clauses field now displays:

StockNumber > 400000 ANDStockNumber < 500000

8 Click OK.

The WHERE Clauses dialog box closes. The Where field and SQLstatement display the Where Clause you specified.

9 Assign the query results to the MATLAB workspace variable A.

10 Click Execute.

3-31

Page 68: Database Toolbox™ II

3 Using Visual Query Builder

11 To view the results, enter A in the Command Window:

12 Save this query as basic_where.qry.

Grouping StatementsUse the WHERE Clauses dialog box to group query statements. In thisexample, modify basic_where.qry to retrieve data where sales in January,February, or March exceed 1500 units, if sales in each month exceed 1000units.

To modify basic_where.qry:

1 Click Where in VQB. The WHERE Clauses dialog box appears.

2 Modify the query to retrieve data if sales in January, February, or Marchexceed 1500 units.

3-32

Page 69: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

a In Current clauses, select StockNumber < 500000 and click Edit.

b For Operator, select OR and click Apply.

c In Fields, select January. For Relation, select > and enter 1500 in itsfield. For Operator, select OR. Click Apply.

d Repeat step c twice, specifying February and March in Fields.

The WHERE Clauses dialog box now looks as follows.

3 Group the criteria that require sales in each month to exceed 1500 units.

a In Current clauses, select the statement January > 1500 OR. PressShift+click to select February > 1500 OR and March > 1500 also.

b Click Group.

An opening parenthesis is added before January and a closingparenthesis is added after March > 1500, indicating that thesestatements are evaluated as a group.

3-33

Page 70: Database Toolbox™ II

3 Using Visual Query Builder

4 Modify the query to retrieve data if sales in each month exceed 1000 units.

a Select March > 1500 ) in Current clauses and click Edit.

b Select AND for Operator and click Apply.

c Select January in Fields. Select > for Relation and enter 1000 in itsfield. Select AND for Operator. Click Apply.

d Repeat step c twice, specifying February and March in Fields.

The WHERE Clauses dialog box now looks as follows.

3-34

Page 71: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

e Click OK.

The WHERE Clauses dialog box closes. The SQL statement dialog boxdisplays the modified where clause.

5 Assign the query results to theMATLAB workspace variable AA.

6 Click Execute to run the query.

3-35

Page 72: Database Toolbox™ II

3 Using Visual Query Builder

7 To view the results, enter AA in the MATLAB Command Window.

Removing Grouping of StatementsTo use the WHERE Clauses dialog box to remove grouping criteria from theprevious example:

1 In Current clauses, select (January > 1000 AND.

2 Press Shift+click to select February > 1000 AND and March > 1000) also.

3 Click Ungroup.

The parentheses are removed from the statements, indicating that theirgrouping is removed.

Displaying Results in a Specified OrderUse Order by in Advanced query options to specify the order in whichquery results display.

This example uses the basic_where.qry query you created in “RetrievingData That Meets Specified Criteria” on page 3-29. The results ofbasic_where.qry are sorted so that January is the primary sort field,February the secondary, and March the last. Results for January andFebruary appear in ascending order, and results for March appear indescending order.

To specify the order in which results appear in basic_where.qry:

3-36

Page 73: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

1 Load basic_where.qry.

2 Set the Data return format preference to cellarray.

3 Set Read NULL numbers to NaN.

4 In Advanced query options, select Order by.

The ORDER BY Clauses dialog box appears.

5 Enter values for the Sort key number and Sort order fields for theappropriate Fields.

To specify January as the primary sort field and display results inascending order:

a In Fields, select January.

b For Sort key number, enter 1.

c For Sort order, select Ascending.

d Click Apply.

The Current clauses area now displays:

January ASC

3-37

Page 74: Database Toolbox™ II

3 Using Visual Query Builder

6 To specify February as the second sort field and display results inascending order:

a In Fields, select February.

b For Sort key number, enter 2.

c For Sort order, select Ascending.

d Click Apply.

The Current clauses area now displays:

January ASCFebruary ASC

7 To specify March as the third sort field and display results in descendingorder:

a In Fields, select March.

b For Sort key number, enter 3.

c For Sort order, select Descending.

d Click Apply.

The Current clauses area now displays:

January ASCFebruary ASCMarch DESC

8 Click OK.

The ORDER BY Clauses dialog box closes. The Order by field and theSQL statement in VQB display the specified Order By clause.

9 Assign the query results to the MATLAB workspace variable B.

10 Click Execute to run the query.

3-38

Page 75: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

11 To view the results, enter B in the MATLAB Command Window. Enter A todisplay the unordered query results and compare them to B. Your resultslook as follows:

For B, results are first sorted by January sales, in ascending order. Thelowest value for January sales, 1200 (for item number 400455), appearsfirst. The highest value, 5000 (for item number for 400345), appears last.

For items 400999, 400314, and 400876, January sales were 3000.Therefore, the second sort key, February sales, applies. February salesappear in ascending order: 1500, 2400, and 2400 respectively.

For items 400314 and 400876, February sales were 2400, so the thirdsort key, March sales, applies. March sales appear in descending order:1800 and 1500, respectively.

Using Having Clauses to Refine Group by Results

Using the HAVING Clauses Dialog BoxUse the Having function to refine the results of a Group By clause.

3-39

Page 76: Database Toolbox™ II

3 Using Visual Query Builder

After specifying a group-by clause in Advanced query options, clickHaving. The HAVING Clauses dialog box appears.

1 From the Fields list box, select the entry whose value to restrict.

2 Define the Condition for the selected field, as described in “RetrievingData That Meets Specified Criteria” on page 3-29.

3 Select Operator to add another condition.

4 Click Apply to create the clause.

The subquery appears in the Current clauses area.

5 Repeat steps 1 through 4 to add more conditions as needed.

6 Change the clauses as needed:

• To edit a clause:

a Select the clause from Current clauses and click Edit.

b Modify the Fields, Condition, and Operator fields as needed.

c Click Apply.

• To group clauses:

3-40

Page 77: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

d Select the clauses to group from Current clauses. Press Ctrl+clickor Shift+click to select multiple clauses.

e Click Group. Parentheses are added around the set of clauses.

To ungroup clauses, select the clauses and then click Ungroup.

• To delete a clause, Select the clause from Current clauses and clickDelete. Use Ctrl+click or Shift+click to select multiple clauses.

7 Specify a subquery in the HAVING Clauses dialog box, as needed. Formore information, see “Creating Subqueries for Values from MultipleTables” on page 3-42.

8 Click OK.

The HAVING Clauses dialog box closes. The SQL statement in the VisualQuery Builder dialog box updates to reflect the specified having clause.

Example: Using Having ClausesThis example restricts the results from basic_where.qry to sales greaterthan 2000 for January and February:

1 In Advanced query options, click Having. The HAVING Clauses dialogbox appears.

2 For January:

a Select > as the Relation Condition.

b Enter 2000 as the Relation value.

c Select the AND Operator.

d Click Apply.

3 For February:

a Select > as the Relation Condition.

b Enter 2000 as the Relation value.

c Click Apply. The HAVING Clauses dialog box appears as follows.

3-41

Page 78: Database Toolbox™ II

3 Using Visual Query Builder

4 Click OK.

The HAVING Clauses dialog box closes. The SQL statement field in theVQB dialog box reflects the specified Having clause.

5 Assign a MATLAB workspace variable C, and click Execute to run thequery.

C =[3000] [2400][5000] [3500]

Compare these results to those in “Displaying Results in a Specified Order”on page 3-36.

Creating Subqueries for Values from Multiple TablesUse the Where feature in Advanced query options to create subqueries.Creating subqueries in this way is referred to as nested SQL.

This example uses basic.qry, which you created in “Saving Queries”.

The salesVolume table has sales volumes and stock number fields, but noproduct description field. The productTable has product description andstock number fields, but no sales volumes. This example retrieves the stocknumber for the product whose description is Building Blocks from the

3-42

Page 79: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

productTable table. It then gets the sales volume values for that stocknumber from the salesVolume table.

1 Load basic.qry.

2 Set the Data return format Preference to cellarray and Read NULLnumbers as to NaN.

3 Click Where in Advanced query options.

The WHERE Clauses dialog box appears.

4 Click Subquery.

The Subquery dialog box appears.

3-43

Page 80: Database Toolbox™ II

3 Using Visual Query Builder

5 In Tables, select productTable, which includes the association betweenthe stock number and the product description. The fields in that tableappear.

6 In Fields, select stockNumber, the field that is common to this table andthe table from which you are retrieving results.

The statement SELECT stockNumber FROM productTable is created in theSQL subquery statement.

7 Limit the query to product descriptions that are Building Blocks.

a In Fields in Subquery WHERE clauses, select productDescription.

b For Condition, select Relation.

c In the drop-down list to the right of Relation, select =.

d In the field to the right of the drop-down list, enter 'Building Blocks'.

e Click Apply.

The clause appears in the Current subquery WHERE clauses fieldand is added to the SQL subquery statement.

3-44

Page 81: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

8 Click OK to close the Subquery dialog box.

9 In the WHERE Clauses dialog box, click Apply.

This updates the Current clauses area using the subquery criteriaspecified in steps 3 through 8.

3-45

Page 82: Database Toolbox™ II

3 Using Visual Query Builder

10 In the WHERE Clauses dialog box, click OK.

The WHERE Clauses dialog box closes. The SQL statement in the VQBdialog box updates.

11 Assign the query results to the MATLAB workspace variable C.

12 Click Execute.

13 Type C at the prompt in the MATLAB Command Window to see the results.

14 The results are for item 400345, which has the product descriptionBuilding Blocks, although that is not evident from the results. Createand run a query to verify that the product description is Building Blocks:

a For Data source, select dbtoolboxdemo.

b In Tables, select productTable.

c In Fields, select stockNumber and productDescription.

d Assign the query results to theMATLAB workspace variable P.

e Click Execute.

3-46

Page 83: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

f Type P at the prompt in the MATLAB Command Window to view theresults.

The results show that item 400345 has the product description BuildingBlocks. In the next section, you create a query that includes productdescription in the results.

Note You can include only one subquery in a query using VQB; you caninclude multiple subqueries using Database Toolbox functions.

Creating Queries That Include Results from MultipleTablesA query whose results include values from multiple tables is said to perform ajoin operation in SQL.

This example retrieves sales volumes by product description. It is like theone in “Creating Subqueries for Values from Multiple Tables” on page 3-42,but this example creates a query that returns product description ratherthan stock number.

The salesVolume table has sales volume and stock number fields, butno product description field. The productTable table has productdescription and stock number fields, but no sales volume field. To createa query that retrieves data from both tables and equates the stock numberfrom productTable with the stock number from salesVolume:

3-47

Page 84: Database Toolbox™ II

3 Using Visual Query Builder

1 Set the Data return format preference to cellarray and the ReadNULL numbers as preference to NaN.

2 For Data operation, click Select.

3 For Data source, select dbtoolboxdemo.

The Catalog, Schema, and Tables for dbtoolboxdemo appear.

Do not specify Catalog or Schema.

4 In Tables, select the tables from which you want to retrieve data. For thisexample, press Ctrl+click and select both productTable and salesVolume.

The fields (columns) in those tables appear in Fields. Fieldnames appear in the format tableName.fieldName. Therefore,productTable.stockNumber indicates the stock number in the producttable and salesVolume.StockNumber indicates the stock number in thesales volume table.

5 In Fields, press Ctrl+click to select the following fields:

• productTable.productDescription

• salesVolume.January

• salesVolume.February

• salesVolume.March

6 In this example, the Where clause equates the productTable.stockNumberwith the salesVolume.StockNumber, so that product description isassociated with sales volumes in the query results.

In Advanced query options, click Where to associate fields fromdifferent tables. The WHERE Clauses dialog box appears.

7 In the WHERE clauses dialog box:

a In Fields, select productTable.stockNumber.

b For Condition, select Relation.

c In the drop-down list to the right of Relation, select =.

3-48

Page 85: Database Toolbox™ II

Fine-Tuning Queries Using Advanced Query Options

d In the field to the right of the drop-down list, entersalesVolume.StockNumber.

e Click Apply.

The clause appears in the Current clauses field.

f Click OK to close the WHERE Clauses dialog box. The Where field andSQL statement in VQB display the Where clause.

8 Assign the query results to theMATLAB workspace variable P1.

9 Click Execute to run the query.

10 Type P1 in the MATLAB Command Window.

P1 =

'Victorian Doll' [1400] [1100] [ 981]'Train Set' [2400] [1721] [1414]'Engine Kit' [1800] [1200] [ 890]'Painting Set' [3000] [2400] [1800]'Space Cruiser' [4300] [ NaN] [2600]'Building Blocks' [5000] [3500] [2800]'Tin Soldier' [1200] [ 900] [ 800]'Sail Boat' [3000] [2400] [1500]'Slinky' [3000] [1500] [1000]'Teddy Bear' [ NaN] [ 900] [ 821]

3-49

Page 86: Database Toolbox™ II

3 Using Visual Query Builder

Additional Advanced Query OptionsFor more information on advanced query options, choose an option and clickHelp in its dialog box. For example, click Group by in Advanced queryoptions, and then click Help in the Group by Clauses dialog box.

3-50

Page 87: Database Toolbox™ II

Retrieving BINARY and OTHER Data Types

Retrieving BINARY and OTHER Data TypesThis example shows how to retrieve data of types BINARY and OTHER, whichmay require manipulation before it can undergo MATLAB processing. Toretrieve images using the dbtoolboxdemo data source and a sample file thatparses image data, matlabroot/toolbox/database/vqb/parsebinary.m:

1 For Data Operation, select Select.

2 In Data source, select dbtoolboxdemo.

3 In Tables, select Invoive.

4 In Fields, select InvoiceNumber and Receipt (which contains bitmapimages).

5 Select Query > Preferences.

6 In the Data return format field, specify cellarray.

7 As the MATLAB workspace variable, specify A.

8 Click Execute to run the query.

3-51

Page 88: Database Toolbox™ II

3 Using Visual Query Builder

9 Type A in the MATLAB Command Window to view the query results.

A =

[1] [21626x1 int8][2] [21626x1 int8][3] [21722x1 int8][4] [21626x1 int8][5] [21626x1 int8][6] [21626x1 int8][7] [21626x1 int8][8] [21626x1 int8][9] [21626x1 int8]

10 Assign the first element in A to the variable photo.

photo = A{1,2};

11 Make sure your current folder is writable.

12 Run the sample program parsebinary, which writes the retrieved data toa file, strips ODBC header information, and displays photo as a bitmapimage.

cd I:\MATLABFiles\myfilesparsebinary(photo, 'BMP');

3-52

Page 89: Database Toolbox™ II

Retrieving BINARY and OTHER Data Types

For more information on parsebinary, enter help parsebinary, or viewthe parsebinary file in the MATLAB Editor/Debugger by entering openparsebinary in the Command Window.

3-53

Page 90: Database Toolbox™ II

3 Using Visual Query Builder

Importing and Exporting BOOLEAN Data

In this section...

“Importing BOOLEAN Data from Databases” on page 3-54

“Exporting BOOLEAN Data to Databases” on page 3-57

Importing BOOLEAN Data from DatabasesBOOLEAN data is imported from databases into the MATLAB workspace asdata type logical. This data has a value of 0 (false) or 1 (true), and is storedin a cell array or structure.

This example imports data from the Invoice table in the dbtoolboxdemodatabase into the MATLAB workspace.

1 Set Data return format to cellarray.

2 For Data operation, choose Select.

3 In Data source, select dbtoolboxdemo.

4 In Tables, select Invoice.

5 In Fields, select Paid and InvoiceNumber.

6 Assign the query results to the MATLAB workspace variable D.

7 Click Execute to run the query.

VQB retrieves a 10-by-2 array.

8 Enter D in the MATLAB Command Window. 10 records are returned:

D =

[ 2101] [0][ 3546] [1][33116] [1][34155] [0][34267] [1]

3-54

Page 91: Database Toolbox™ II

Importing and Exporting BOOLEAN Data

[37197] [1][37281] [0][41011] [1][61178] [0][62145] [1]

9 Compare these results to the data in Microsoft Access.

3-55

Page 92: Database Toolbox™ II

3 Using Visual Query Builder

10 In the VQB Data area, double-click D to view its contents in the Variableseditor.

3-56

Page 93: Database Toolbox™ II

Importing and Exporting BOOLEAN Data

Exporting BOOLEAN Data to DatabasesLogical data is exported from the MATLAB workspace to a database as typeBOOLEAN. This example adds two rows of data to the Invoice table in thedbtoolboxdemo database.

1 In the MATLAB workspace, create I, the structure you want to export.

I.InvoiceNumber{1,1}=456789;I.Paid{1,1}=logical(0);I.InvoiceNumber{2,1}=987654;I.Paid{2,1}=logical(1);

2 For Data operation, choose Insert.

3 In Data source, select dbtoolboxdemo.

4 In Tables, select Invoice.

5 In Fields, select Paid and InvoiceNumber.

6 Assign results to the MATLAB workspace variable I.

7 Click Execute to run the query.

VQB inserts two new rows into the Invoice table.

View the table in Microsoft Access to verify that the data was correctlyinserted.

3-57

Page 94: Database Toolbox™ II

3 Using Visual Query Builder

3-58

Page 95: Database Toolbox™ II

Saving Queries in Files

Saving Queries in Files

In this section...

“About Generated Files” on page 3-59

“VQB Query Elements in Generated Files” on page 3-60

About Generated FilesSelect Query > Generate MATLAB File to create a file that contains theequivalent Database Toolbox functions required to run an existing querythat was created in VQB. Edit the file to include MATLAB or related toolboxfunctions, as needed. To run the query, execute the file.

The following is an example of a file generated by VQB:

% Set preferences with setdbprefs.

s.DataReturnFormat = 'cellarray';

s.ErrorHandling = 'store';

s.NullNumberRead = 'NaN';

s.NullNumberWrite = 'NaN';

s.NullStringRead = 'null';

s.NullStringWrite = 'null';

s.JDBCDataSourceFile = '';

s.UseRegistryForSources = 'yes';

s.TempDirForRegistryOutput = '';

s.FetchInBatches = 'yes';

s.FetchBatchSize = '10000'

setdbprefs(s)

% Make connection to database. Note that the password has been omitted.

% Using ODBC driver.

conn = database('dbtoolboxdemo','','password');

% Read data from database.

e = exec(conn,'SELECT ALL StockNumber,January,February FROM salesVolume');

e = fetch(e);

close(e)

3-59

Page 96: Database Toolbox™ II

3 Using Visual Query Builder

Close database connection.

close(conn)

VQB Query Elements in Generated FilesThe following VQB query elements do not appear in generated files:

• Generated code files do not include MATLAB workspace variables to whichyou assigned query results in the VQB query. The file assigns the queryresults to e; access these results using the variable e.Data. For example,you can add a statement to the file that assigns a variable name to e.Dataas follows:

myVar = e.Data

• For security reasons, generated files do not include passwords requiredto connect to databases. Instead, the database statement includes thestring 'password' as a placeholder. To run files to connect to databasesthat require passwords, substitute your password for the string passwordin the database statement.

3-60

Page 97: Database Toolbox™ II

Using Database Explorer

Using Database Explorer

In this section...

“About Database Explorer” on page 3-61

“Workflow” on page 3-62

“Configure Your Environment” on page 3-62

“Database Connection Error Messages” on page 3-74

“Set Database Preferences” on page 3-76

“Display Data from a Single Database Table” on page 3-78

“Join Data from Multiple Database Tables” on page 3-80

“Define Query Criteria to Refine Results” on page 3-85

“Query Rules Using the SQL Criteria Panel” on page 3-87

“Query Example Using a Left Outer Join” on page 3-89

“Work with Multiple Databases” on page 3-98

“Import Data to the MATLAB Workspace” on page 3-98

“Save Queries as SQL Code” on page 3-101

“Generate MATLAB Code” on page 3-102

About Database Explorerdexplore starts Database Explorer, which is a Database Toolbox app forconnecting to a database and importing data to the MATLAB workspace.

Database Explorer is an interactive app that lets you:

• Create and configure JDBC and ODBC data sources.

• Establish multiple connections to databases.

• Select tables and columns of interest.

• Fine-tune selection using SQL query criteria.

• Preview selected data.

3-61

Page 98: Database Toolbox™ II

3 Using Visual Query Builder

• Import selected data into the MATLAB workspace.

• Save generated SQL queries.

• Generate MATLAB code.

WorkflowThe workflow for using Database Explorer is:

1 Set up an ODBC or JDBC connection to your database.

2 Connect to the database.

3 Select tables and columns of interest.

4 Use query criteria to fine-tune display results.

5 Select data and import it into the MATLAB workspace.

6 Use the Database Explorer tabbed interface to open multiple databases.

7 Save queries as an SQL script to run later.

8 Generate MATLAB code.

Configure Your EnvironmentBefore using Database Explorer to connect to a database, you must set up adata source. A data source consists of:

• Data that the toolbox accesses

• Information required to find the data, such as driver, folder, server, ornetwork names

Data sources interact with ODBC drivers or JDBC drivers. An ODBC driver isa standard Microsoft Windows interface that enables communication betweendatabase management systems and SQL-based applications. A JDBC driveris a standard interface that enables communication between applicationsbased on Oracle Java and database management systems.

3-62

Page 99: Database Toolbox™ II

Using Database Explorer

Database Toolbox software is based on Java. It uses a JDBC/ODBC bridge toconnect to the ODBC driver of a database, which is automatically installed aspart of the MATLAB JVM.

This figure illustrates how drivers interact with Database Toolbox software.

6����� ������"�

5478��6����� ������"�

9#*:;<#*:*��.�

#�������(�����3

#�������(�����3

9#*:#����� #�������

<#*:#����� #�������

Tip Some Windows systems support both ODBC and JDBC drivers. On suchsystems, JDBC drivers generally provide better performance than ODBCdrivers because the ODBC/JDBC bridge is not used to access databases.

Before You BeginBefore you can use Database Explorer with the examples in thisdocumentation, do the following:

1 Set up the data sources that are provided with Database Toolbox.

Caution If you have previously used Visual Query Builder(querybuilder) to access a JDBC data source, before starting DatabaseExplorer for the first time, you must execute the following command:

setdbprefs('JDBCDataSourceFile', '')

2 Configure the data sources for use with your database driver.

• If you are using an ODBC driver, see “Configure ODBC Data Sources”on page 3-64.

3-63

Page 100: Database Toolbox™ II

3 Using Visual Query Builder

• If you are using a JDBC driver, see “Configure JDBC Data Sources”on page 3-69.

Set Up the dbtoolboxdemo Data SourceThe dbtoolboxdemo data source uses the tutorial database located inmatlabroot/toolbox/database/dbdemos/tutorial.mdb.

To set up this data source:

1 Copy tutorial.mdb into a folder to which you have write access.

2 Confirm you have write access to tutorial.mdb.

3 Open tutorial.mdb from the MATLAB Current Folder by right-clickingthe file and selecting Open Outside MATLAB. The file opens in MicrosoftAccess.

Note You might need to convert the database to the version of Access youare currently running. For example, beginning in Microsoft Access 2007,you see the option to save as *.accdb. For more information, consult yourdatabase administrator.

Configure ODBC Data SourcesWhen setting up a data source for use with an ODBC driver, the targetdatabase can be located on a PC running the Windows operating system oron another system to which the PC is networked. These instructions usethe Microsoft ODBC Data Source Administrator Version 6.1 for the U.S.English version of Microsoft Access 2010 for Windows systems. If you havea different configuration, you might need to modify these instructions. Formore information, consult your database administrator.

1 Close open databases, including tutorial.mdb in the database program.

2 Start Database Explorer by clicking the Apps tab on the MATLABToolstrip and then selecting Database Explorer from the DatabaseConnectivity and Reporting section in the apps gallery. Alternatively,at the command line, enter:

3-64

Page 101: Database Toolbox™ II

Using Database Explorer

dexplore

If no data sources are set up, a message box opens. Click OK to dismissthe message. Otherwise, you are prompted to Connect to a data source.Click Cancel to dismiss this prompt.

3 Click the Database Explorer tab and then select New > ODBC to openthe ODBC Data Source Administrator dialog box to define the ODBC datasource.

Requirement When using a 32-bit version of Microsoft Office, you mustalso use a 32-bit version of MATLAB to complete the remaining steps.

4 Click the User DSN tab.

5 Click Add.

3-65

Page 102: Database Toolbox™ II

3 Using Visual Query Builder

A list of installed ODBC drivers appears in the Create New Data Sourcedialog box.

6 Select Microsoft Access Driver (*.mdb, *.accdb) and click Finish.

The ODBC Microsoft Access Setup dialog box for your driver opens. Thedialog box for your driver might differ from the following.

3-66

Page 103: Database Toolbox™ II

Using Database Explorer

7 Enter dbtoolboxdemo as the data source name.

8 Enter tutorial database as the description.

9 Select the database for this data source to use. For some drivers, you canskip this step. If you are unsure about skipping this step, consult yourdatabase administrator.

a In the ODBC Microsoft Access Setup dialog box, click Select.

3-67

Page 104: Database Toolbox™ II

3 Using Visual Query Builder

b Specify the database you want to use. For the dbtoolboxdemo datasource, select tutorial.mdb.

c If your database is on a system to which your PC is connected:

i Click Network. The Map Network Drive dialog box opens.

ii Specify the folder containing the database you want to use.

iii Click Finish.

d Click OK to close the Select Database dialog box.

10 In the ODBC Microsoft Access Setup dialog box, click OK.

11 Repeat steps 7 through 10 with the following changes to define the datasource for any additional databases that you want to use.

The ODBC Data Source Administrator dialog box displays thedbtoolboxdemo and any additional data sources that you have added inthe User DSN tab.

3-68

Page 105: Database Toolbox™ II

Using Database Explorer

12 Click OK to close the dialog box.

Configure JDBC Data Sources

1 Find the name of the JDBC driver file. This file is provided by yourdatabase vendor. The name and location of this file differ for each system.If you do not know the name or location of this file, consult your databaseadministrator.

Caution If you have previously used Visual Query Builder(querybuilder) to access a JDBC data source, before starting DatabaseExplorer for the first time, you must execute the following command:

setdbprefs('JDBCDataSourceFile', '')

Then follow these instructions to set up the JDBC data source usingDatabase Explorer.

3-69

Page 106: Database Toolbox™ II

3 Using Visual Query Builder

2 Specify the location of the JDBC drivers file in the MATLAB Java class pathby adding this file’s path to javaclasspath.txt file. MATLAB loads thestatic class path at the start of each session. The static path offers betterclass loading performance than the dynamic path. To add folders to thestatic path, create the file javaclasspath.txt, and then restart MATLAB.

Create an ASCII file in your preferences folder named javaclasspath.txt.To view the location of the preferences folder, type:

prefdir

Each line in the file is the path name of a folder or jar file. For example:

d:\work\javaclasses

To simplify the specification of folders in cross-platform environments, useany of these macros: $matlabroot, $arch, and $jre_home. You can alsocreate a javaclasspath.txt file in your MATLAB startup folder. Classesspecified in this file override classes specified in the javaclasspath.txtfile in the preferences folder.

Note MATLAB reads the static class path only at startup. If you editjavaclasspath.txt or change your .class files while MATLAB isrunning, you must restart MATLAB to put those changes into effect.

If the drivers file is not located where javaclasspath.txt indicates,errors do not appear, and Database Explorer does not establish a databaseconnection.

For more information, see “Bringing Java Classes into MATLABWorkspace”.

3 Close the open database, tutorial.mdb, in the database program.

4 Start Database Explorer by clicking the Apps tab on the MATLABToolstrip and then selecting Database Explorer from the DatabaseConnectivity and Reporting section in the apps gallery. Alternatively,at the command line, enter:

dexplore

3-70

Page 107: Database Toolbox™ II

Using Database Explorer

5 Click the Database Explorer tab and then select New > JDBC to openthe Create a New JDBC data source dialog box.

6 Use the following table to set up JDBC drivers for use with DatabaseExplorer.

a Using the Create a New JDBC data source dialog box, this table describesthe fields that you use to define your JDBC data source. For examplesof syntax used in these fields, see “JDBC Driver Name and DatabaseConnection URL” on page 5-36 on the database function reference page.

3-71

Page 108: Database Toolbox™ II

3 Using Visual Query Builder

Field Description

Data SourceName

The name you assign to the data source. For somedatabases, the Name must match the name of thedatabase as recognized by the machine it runs on.

Vendor The vendor’s name for the data source. When usingOther:

• Driver — The JDBC driver name (sometimesreferred to as the class that implements the JavaSQL driver for your database).

• URL — The JDBC URL object, of the formjdbc:subprotocol:subname. subprotocol isa database type. subname can contain otherinformation used by Driver, such as the location ofthe database and/or a port number. It can take theform //hostname:port/databasename.

Note When using Other as the Vendor, your drivermanufacturer’s documentation specifies the Driverand URL formats. You might need to consult yourdatabase system administrator for this information.

ServerName

Server name.

PortNumber

Server port number.

AuthenticationType

(Microsoft SQL Server only) Server or Windowsauthentication.

Driver Type (Oracle only) Driver type is thin or oci.

Username User name to access the database.

Password Password.

Database Database name.

3-72

Page 109: Database Toolbox™ II

Using Database Explorer

b In the Create a New JDBC data source dialog box, click Save.

c If this is the first time you are creating a data source using DatabaseExplorer, the New file to store JDBC connection parameters dialog boxopens. Use this dialog box to create a MAT-file that saves your specifieddata source information for future Database Explorer sessions.

Navigate to the folder where you want to put the MAT-file, specify aname for it that includes a .mat extension, and click Save.

d Test the connection by clicking Test.

If your database requires a user name and password, a dialog boxprompting you to supply them opens. Enter values into these fields andclick OK.

A confirmation dialog box states that the database connection succeeded.

e To add more data sources, repeat steps 5 and 6 for each new data source.

Note You can use tabs in Database Explorer to access different datasources. All of the data sources created using Database Explorer arestored in a single MAT-file for easy access. This MAT-file name is storedin setdbprefs('JDBCDataSourceFile') and is valid for all MATLABsessions.

Connect to Data SourceAfter configuring your OBDC or JBDC data sources, use Database Explorerto connect to the database.

1 Start Database Explorer by clicking the Apps tab on the MATLABToolstrip and then selecting Database Explorer from the DatabaseConnectivity and Reporting section in the apps gallery. Alternatively,at the command line, enter:

dexplore

2 Select your data source from the Connect to a Data Source dialog box orclick Cancel and then click the Database Explorer tab and then clickConnect to select your data source.

3-73

Page 110: Database Toolbox™ II

3 Using Visual Query Builder

3 Select your data source from the Data Sources list and enter your username and password.

Database Connection Error Messages

Connection Error Messages and Probable Causes

Vendor Error Message Probable Causes

All Unable to find JDBC driver. • Path to the JDBC driver jar file isnot on the static or dynamic classpath.

• Incorrect driver name providedwhile using the 'driver' and'url' syntax.

All [Microsoft][ODBC Driver Manager]The specified DSN contains anarchitecture mismatch between Driverand Application

You tried to open a 32-bit applicationwhen running MATLAB in 64-bitmode. Restart MATLAB to run in32-bit mode using the commandmatlab win32.

3-74

Page 111: Database Toolbox™ II

Using Database Explorer

Connection Error Messages and Probable Causes (Continued)

Vendor Error Message Probable Causes

Microsoft SQLServer

The TCP/IP connection to the hosthostname, port portnumber has failed.Error: “null. Verify the connectionproperties, check that an instance ofSQL Server is running on the host andaccepting TCP/IP connections at theport, and that no firewall is blockingTCP connections to the port.”

Incorrect server name or portnumber. Microsoft SQL Serveruses a dynamic port for JDBC andthe value should be verified usingMicrosoft SQL Server ConfigurationManager.

Microsoft SQLServer

This driver is not configured forintegrated authentication.

The Microsoft SQL Server Windowsauthentication library is not addedto librarypath.txt. For moreinformation, see the databaseexample for Microsoft SQL ServerAuthenticated Database Connection.

Microsoft SQLServer

Invalid string or buffer length. 64-bit ODBC driver error. Use aJDBC driver or the native ODBCinterface instead.

MySQL Access denied for user'user'@'machinename' (usingpassword: YES)

Incorrect user name and passwordcombination.

MySQL Communications link failure.The last packet sent successfully tothe server was 0 milliseconds ago. Thedriver has not received any packetsfrom the server.

Incorrect server name or portnumber.

MySQL Unknown database 'databasename'. Provided database name is incorrect.

3-75

Page 112: Database Toolbox™ II

3 Using Visual Query Builder

Connection Error Messages and Probable Causes (Continued)

Vendor Error Message Probable Causes

Oracle Error when connecting to Oracle oci8database using JDBC driver:

Error using com.mathworks.toolbox.database.databaseConnect/makeDaabaseConnection

Java exception occurred:

java.lang.UnsatisfiedLinkError: no ocijdbc11 in

java.library.pathat

java.lang.ClassLoader.loadLibrary(Unknown Source)at

java.lang.Runtime.loadLibrary0.......

MATLAB cannot find the OracleDLL that the oci8 drivers need. Tocorrect the problem, add the path forthe location of the Oracle DLLs to$MATLAB/toolbox/local/librarypath.txt.

Oracle Invalid Oracle URL specified:

OracleDataSource.makeURL

DriverType parameter is notspecified.

Oracle The Network Adapter could notestablish the connection.

Either Server or Portnumber is notspecified or has an incorrect value.

Set Database Preferences1 Select Preferences from the Data Explorer Toolstrip to open the DatabaseToolbox Database Explorer Preferences dialog box. These preferencesettings apply only to Database Explorer.

3-76

Page 113: Database Toolbox™ II

Using Database Explorer

2 Specify the Preferences settings that apply to Database Explorer asdescribed in the following table.

PreferenceAllowableValues Description

DataPreviewsize:

5 to 10,000rows

The number of rows you see in the Data Preview pane ofDatabase Explorer.

Importbatch size:

1,000 to1,000,000rows

The number of rows fetched at one time from a database. Whenimporting large amounts of data using Database Explorer, tunethis value for optimum performance. For more information, see“Preference Settings for Large Data Import” on page 3-10.

3-77

Page 114: Database Toolbox™ II

3 Using Visual Query Builder

From Database Toolbox Database Explorer Preferences dialog box, selectDatabase Toolbox to manage additional preferences for DatabaseToolbox. For more information, see “Working with Preferences” on page3-6. Alternatively, you can use setdbprefs to specify preferences for theretrieved data.

3 Click OK.

Display Data from a Single Database TableAfter connecting to your database, you can display data in database tablesin the Data Preview pane.

1 Display data in the Data Preview pane by opening the database tableof interest in the Database Browser pane. When a database table isselected in the Database Browser pane, it is highlighted and there is acorresponding entry in the SQL Criteria panel on the Database ExplorerToolstrip. The SQL Criteria panel is where you enter query conditionsfor the selected table.

For any given table, you can select the table information any of three ways:

• Click to highlight the database table name. This does not display data inthe Data Preview pane but does update the SQL Criteria panel.

• Select (All) to choose all table columns and display them in the DataPreview pane.

• Select specific check boxes to choose individual table columns anddisplay them in the Data Preview pane.

Note The order of the columns in the Data Preview pane matches theorder in which you select them in the Database Browser pane.

3-78

Page 115: Database Toolbox™ II

Using Database Explorer

2 Select (All) to choose all database columns or select check boxes for specifictable columns.

3-79

Page 116: Database Toolbox™ II

3 Using Visual Query Builder

3 To change your display, select or clear check boxes in the DatabaseBrowser pane. The data updates in the Data Preview pane.

The Data Preview pane displays a limited number of rows. The totalnumber of rows actually selected in the database appears at the right ofthe display. You can change the display size by clicking Preferences andadjusting the Data Preview size.

Join Data from Multiple Database TablesAfter connecting to your database, you can display data from database tablesin the Data Preview pane.

1 Display data in the Data Preview pane by opening the desired databasetable in the Database Browser pane. The SQL Criteria panel on theDatabase Explorer Toolstrip is updated.

3-80

Page 117: Database Toolbox™ II

Using Database Explorer

2 When you select additional tables in the Database Browser pane, theSQL Criteria panel is updated.

3-81

Page 118: Database Toolbox™ II

3 Using Visual Query Builder

3 Display the contents for the selected table using the SQL Criteria panelto define a join of the selected tables. Click the drop-down lists to specify

3-82

Page 119: Database Toolbox™ II

Using Database Explorer

which table column to join the selected tables. The join results appearin the Data Preview pane.

3-83

Page 120: Database Toolbox™ II

3 Using Visual Query Builder

3-84

Page 121: Database Toolbox™ II

Using Database Explorer

Define Query Criteria to Refine ResultsDatabase Browser selections and SQL criteria work together.

Using the Database Browser pane and the SQL Criteria panel, you candefine query conditions and display the results in the Data Preview pane.Each row in the SQL Criteria panel has drop-down controls to define SQLquery conditions. You can create SQL query conditions that span multiplerows in the SQL Criteria panel.

Note When the right side of a query condition is a custom value that youenter in the text box, you must press the Enter or Tab key for the querycondition to take effect.

3-85

Page 122: Database Toolbox™ II

3 Using Visual Query Builder

Each row in the SQL Criteria panel has four columns to define your SQLquery.

3-86

Page 123: Database Toolbox™ II

Using Database Explorer

Column 1 Column 2 Column 3 Column 4

Column 1defines the SQLcondition typewhere supportedvalues are:

• INNERJOIN

• LEFT JOIN

• RIGHTJOIN

• FULL JOIN

• WHERE

• ORDER BY

• AND

• OR

Column2 definesthe columnnames for allof the tablesselectedin theDatabaseBrowserpane.

Column 3 definesthe mathematicaloperator foreach row of SQLstatements wheresupported valuesare:

• =

• !=

• >

• <

• <=

• >=

• LIKE

• NOT LIKE

• IS

• IN

• NOT IN

• ASC

• DES

Depending on thepreceding conditionof the querystatement, Column4 displays columnnames for all ofthe tables selectedin the DatabaseBrowser pane.

Use multiple rows in the SQL Criteria panel to define multiple SQL querystatements.

Query Rules Using the SQL Criteria PanelThe control options for the SQL Criteria panel depend on your selections inthe Database Browser pane. The SQL Criteria panel supports multiplerows for specifying your query criteria. You can add more rows for theseoptions in the SQL Criteria panel by clicking + or you can remove a rowby clicking -.

3-87

Page 124: Database Toolbox™ II

3 Using Visual Query Builder

• If only one table is selected in the Database Browser pane, the availableoptions for the first query condition areWHERE and ORDER BY.

• If two tables are selected in the Database Browser pane, the availableoptions for the first query condition are:

- INNER JOIN

- LEFT JOIN

- RIGHT JOIN

- FULL JOIN

- WHERE

- ORDER BY

- AND

- OR

• After you apply a condition for a row in the SQL Criteria panel by usingthe Enter or Tab keys, for every subsequent condition that you add, thefirst (leftmost) column contains only those query options that producesemantically correct SQL statements. For example, if the leftmost columnof an applied condition contains an ORDER BY option, if you click + to adda new query option in a new row, the ORDER BY option from the previousrow can only be followed by another ORDER BY option.

In addition, a Join option can only be followed by another JOIN orWHERE and a JOIN option cannot follow a WHERE or ORDER BYoption.

• When defining a new query line in the SQL Criteria panel for anyconditions other than a JOIN, the new SQL line does not take effect untilyou apply the new line. When you apply a condition, all preceding andsucceeding conditions that are not applied are removed from the SQLCriteria panel. Similarly, if you click - to remove a query line, if thatquery line has been applied, all succeeding conditions are removed. If thequery line has not yet been applied, then only that line is removed from theSQL Criteria panel.

• When using a WHERE SQL statement with a mathematical operator, tomatch a string, you must include the string value in' ' to successfully

3-88

Page 125: Database Toolbox™ II

Using Database Explorer

apply the condition. If you use the LIKE or NOT LIKE SQL operator tomatch a string, the ' ' are automatically added to the string value.

Note If you click + to add a new query condition between two previouslyentered conditions, the available query options do not always producesemantically correct SQL statements. In this case, you must ensure thatyour query options are semantically correct. For best results using the SQLCriteria panel, add and apply your conditions in sequence.

Query Example Using a Left Outer JoinThis example demonstrates how to use a query to obtain supplier and productinformation using a LEFT JOIN. To use this example, you must set up adata source for the tutorial.mdb database. For information on setting upthis data source, see “Set Up the dbtoolboxdemo Data Source” on page 3-64.

1 Open tutorial.mdb in Database Explorer and expand the table suppliersand select the fields SupplierName, City, and Country.

3-89

Page 126: Database Toolbox™ II

3 Using Visual Query Builder

2 Expand the table producttable and select the fields productDescriptionand unitCost. The Data Preview pane displays an info messageprompting you to enter a join condition. Also, there are two emptyconditions in the SQL Criteria panel on the Database Explorer Toolstrip.

3-90

Page 127: Database Toolbox™ II

Using Database Explorer

3 From the SQL Criteria panel, in the first (topmost) condition, changethe first combo box for condition type to LEFT JOIN. Change the secondcombo box to suppliers.SupplierNumber. Change the last combo box to

3-91

Page 128: Database Toolbox™ II

3 Using Visual Query Builder

producttable.SupplierNumber. A left join, with the suppliers table onthe left, implies that all the rows in the suppliers table are included in thefinal result, and the rows in suppliers that do not have a match with anyrow in producttable, are padded with null values in the final result.

In the Data Preview, there are 11 rows that match the query conditions.For the supplier named The Great Teddy Bear Company, notice thatthere is a null in the productDescription and a NaN for unitCost. Thisis because there is no product that is supplied by The Great Teddy BearCompany. If the condition type were INNER JOIN instead of LEFT JOIN,this row would not be present in the final result.

3-92

Page 129: Database Toolbox™ II

Using Database Explorer

3-93

Page 130: Database Toolbox™ II

3 Using Visual Query Builder

4 From the SQL Criteria pane, click + at the end of the LEFT JOINcondition to add a new query condition. Change the first combo box toWHERE, the second to suppliers.Country, the third to NOT LIKE. Inthe last text box, type United State and then enter the new conditionusing the Enter or Tab key. The query results display in the DataPreview pane.

3-94

Page 131: Database Toolbox™ II

Using Database Explorer

3-95

Page 132: Database Toolbox™ II

3 Using Visual Query Builder

5 Enter the variable name as data in the text box named untitled locatedabove the table preview, and select Import > Import to import the datadisplayed in the Data Preview pane into MATLAB as a variable nameddata. For more information about using the MATLAB Variables editor, see“View, Edit, and Copy Variables”.

3-96

Page 133: Database Toolbox™ II

Using Database Explorer

3-97

Page 134: Database Toolbox™ II

3 Using Visual Query Builder

Work with Multiple Databases1 If you have not defined the OBDC or JDBC connection for your new datasource, click Open and select ODBC or JDBC and complete the associateddialog box. For more information, see “Configure ODBC Data Sources” onpage 3-64 or “Configure JDBC Data Sources” on page 3-69.

2 Select Connect > Connect... to select your new data source.

3 The new data source appears in a new tab in the Database Browser pane.You can change databases by clicking the associated tab.

Note, you can only use Database Explorer to create SQL queries for asingle database at a time.

In addition, you can work with a different catalog and schema on the samedatabase server as the one connected to your current data source. To changeto a different catalog and schema:

• Select the catalog/schema from the drop-down list in the address bar of theDatabase Browser. For a database system like Microsoft SQL Server thathas a hierarchy of catalogs and schemas, make sure you choose the correctvalue for both in order to access data in your tables.

Import Data to the MATLAB Workspace1 Use the Database Browser pane to select data from a single table or usethe SQL Criteria panel to create a query and display the results in theData Preview pane.

2 Name the MATLAB variable by entering it in the untitled text box in theData Preview pane.

3 Use the Imported Data panel to define the data structure for a MATLABvariable to store the data displayed in the Data Preview pane. Supporteddata structures are:

• Cell Array

• Numeric

• Structure

• Table

3-98

Page 135: Database Toolbox™ II

Using Database Explorer

• Dataset (requires Statistics Toolbox)

4 Select Import > Import to import the data displayed in the DataPreview pane.

3-99

Page 136: Database Toolbox™ II

3 Using Visual Query Builder

Tip When importing large amounts of data, Database Explorer importsdata in batches. The batch size is set to 1,000 rows by default. To changethe batch size, click Preferences and adjust Import batch size.

3-100

Page 137: Database Toolbox™ II

Using Database Explorer

5 (Optional) Display the imported data in the MATLAB workspace using theVariables editor. For more information about using the Variables editor,see “View, Edit, and Copy Variables”.

6 (Optional) Use MATLAB functions to manipulate the data.

Save Queries as SQL CodeYou can save a Database Explorer query as SQL code.

1 Use the Database Browser pane to select data from a single table ormultiple tables. Then use the SQL Criteria panel to create queries anddisplay the results in the Data Preview pane.

2 After you have created a query using the SQL Criteria panel, clickImport > Generate SQL to display the SQL code in the MATLAB Editor.

3-101

Page 138: Database Toolbox™ II

3 Using Visual Query Builder

3 Save the SQL code to a .txt or .sql file. You can then use the SQLstatements to manually rebuild a query using the SQL Criteria panel.

4 Alternatively, you can use the .sql file to import data programmaticallyinto MATLAB by using runsqlscript.

Generate MATLAB CodeYou can generate MATLAB code to automate the steps for accessing data thatyou display in the Data Preview pane.

1 Connect to a data source and then use the Database Browser pane toselect data from a single table or use the SQL Criteria panel to create aquery and display the results in the Data Preview pane.

2 Select Import > Generate Script to display MATLAB code in theMATLAB Editor.

3-102

Page 139: Database Toolbox™ II

Using Database Explorer

3 Save the MATLAB code to a file. You can run this code file from thecommand line to connect to a data source and run a query.

3-103

Page 140: Database Toolbox™ II

3 Using Visual Query Builder

3-104

Page 141: Database Toolbox™ II

4

Using Database ToolboxFunctions

• “Getting Started with Database Toolbox Functions” on page 4-2

• “Importing Data from Databases” on page 4-3

• “Viewing Information About Imported Data” on page 4-5

• “Exporting Data to New Record in Database” on page 4-8

• “Replacing Existing Database Data with Exported Data” on page 4-12

• “Exporting Multiple Records from the MATLAB Workspace” on page 4-14

• “Exporting Data Using the Bulk Insert Command” on page 4-18

• “Retrieving Image Data Types” on page 4-25

• “Working with Database Metadata” on page 4-27

• “Using Driver Functions” on page 4-34

• “About Database Toolbox Objects and Methods” on page 4-36

• “Using the exec Function” on page 4-39

• “Using the fetch Function” on page 4-42

Page 142: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Getting Started with Database Toolbox FunctionsThe following sections provide examples of how to use Database Toolboxfunctions. MATLAB files that include functions used in some of theseexamples are available in matlab/toolbox/database/dbdemos.

Follow these simple examples consecutively when you first start using theproduct. Once you are familiar with Database Toolbox usage, refer to theseexamples as needed.

4-2

Page 143: Database Toolbox™ II

Importing Data from Databases

Importing Data from DatabasesThis example demonstrates a sample workflow on a demonstration databasecalled dbtoolboxdemo.

1 Before you connect to a database, set the maximum time that you want toallow the MATLAB software session to try to connect to a database to 5seconds.

logintimeout(5)

Note If you are connecting to a database using a JDBC connection, youneed to specify different function syntax in this step. For more information,see the logintimeout function reference page.

2 Use the database function to define a MATLAB variable, conn, torepresent the returned connection object. Pass the following argumentsto this function:

• The name of the database, which is dbtoolboxdemo for this example

• The username and password

conn = database('dbtoolboxdemo', 'username', 'password')

Enter conn at the command prompt to see the data.

Note If you are connecting to a database using a JDBC connection, youneed to specify different syntax for the database function. Alternatively,you can use the native ODBC interface for an ODBC connection. For moreinformation, see the database reference page.

3 Use ping to check that the database connection status is successful.

4 Use the exec function to open a cursor and execute an SQL statement.Pass the following arguments to exec:

• conn, the name of the connection object

4-3

Page 144: Database Toolbox™ II

4 Using Database Toolbox™ Functions

• select productNumber from productTable, a SQL statement thatselects the productNumber column of data from the productTable table

curs = exec(conn, 'select productNumber, productDescription from productTable')

The exec function returns the MATLAB variable curs.

5 The returned data contains strings, so you must convert it to a format thatsupports strings. Use setdbprefs to specify the format cellarray:

setdbprefs('DataReturnFormat','cellarray')

6 To stop working now and resume working on the next example at a latertime, close the cursor and the connection as follows:

close(curs);close(conn);

4-4

Page 145: Database Toolbox™ II

Viewing Information About Imported Data

Viewing Information About Imported DataThis example shows how to view information about imported data from thedbtoolboxdemo data source and close the connection to the database usingthe following Database Toolbox functions:

• attr

• close

• cols

• columnnames

• rows

• width

For more information on these functions, seematlab\toolbox\database\dbdemos\dbinfodemo.m.

1 Open the cursor and connection if needed:

conn = database('dbtoolboxdemo', '', '');

curs = exec(conn, 'select productDescription from productTable');

setdbprefs('DataReturnFormat','cellarray');

curs = fetch(curs, 10);

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

2 Use rows to return the number of rows in the data set:

numrows = rows(curs)numrows =

10

3 Use cols to return the number of columns in the data set:

numcols = cols(curs)numcols =

1

4-5

Page 146: Database Toolbox™ II

4 Using Database Toolbox™ Functions

4 Use columnnames to return the names of the columns in the data set:

colnames = columnnames(curs)colnames ='productDescription'

5 Use width to return the column width, or size of the field, for the specifiedcolumn number:

colsize = width(curs, 1)colsize =

50

6 Use attr to view multiple attributes for a column:

attributes = attr(curs)

attributes =

fieldName: 'productDescription'typeName: 'VARCHAR'

typeValue: 12columnWidth: 50

precision: []scale: []

currency: 'false'readOnly: 'false'nullable: 'true'Message: []

Tip To import multiple columns, include a colnum argument in attr tospecify the number of columns whose information you want.

7 Close the cursor.

close(curs);

8 Continue with the next example. To stop working now and resume workingon the next example at a later time, close the connection.

4-6

Page 147: Database Toolbox™ II

Viewing Information About Imported Data

close(conn);

4-7

Page 148: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Exporting Data to New Record in DatabaseThis example does the following:

1 Retrieves sales data from a salesVolume table.

2 Calculates the sum of sales for 1 month.

3 Stores this data in a cell array.

4 Exports this data to a yearlySales table.

You learn to use the following Database Toolbox functions:

• get

• fastinsert

• setdbprefs

For more information on these functions, seematlab\toolbox\database\dbdemos\dbinsertdemo.m.

1 Connect to the data source, dbtoolboxdemo, if needed:

conn = database('dbtoolboxdemo', '', '');

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

2 Use setdbprefs to set the format for retrieved data to numeric:

setdbprefs('DataReturnFormat','numeric')

3 Import ten rows of data the March column of data from the salesVolumetable.

curs = exec(conn, 'select March from salesVolume');curs = fetch(curs);

4 Assign the data to the MATLAB workspace variable AA:

4-8

Page 149: Database Toolbox™ II

Exporting Data to New Record in Database

AA = curs.DataAA =

981141489018002600280080015001000821

5 Calculate the sum of the March sales and assign the result to the variablesumA:

sumA = sum(AA(:))sumA =

14606

6 Assign the month and sum of sales to a cell array to export to a database.Put the month in the first cell of exdata:

exdata(1,1) = {'March'}exdata =

'March'

Put the sum in the second cell of exdata:

exdata(1,2) = {sumA}exdata =

'March' [14606]

7 Define the names of the columns to which to export data. In this example,the column names are Month and salesTotal, from the yearlySalestable in the dbtoolboxdemo database. Assign the cell array containing thecolumn names to the variable colnames:

colnames = {'Month','salesTotal'};

4-9

Page 150: Database Toolbox™ II

4 Using Database Toolbox™ Functions

8 Use the get function to determine the current status of the AutoCommitdatabase flag. This status determines whether the exported data isautomatically committed to the database. If the flag is off, you can undoan update; if it is on, data is automatically committed to the database.

get(conn, 'AutoCommit')ans =on

The AutoCommit flag is set to on, so the exported data is automaticallycommitted to the database.

9 Use the fastinsert function to export the data into the yearlySales table.Pass the following arguments to this function:

• conn, the connection object for the database

• yearlySales, the name of the table to which you are exporting data

• The cell arrays colnames and exdata

fastinsert(conn, 'yearlySales', colnames, exdata)

fastinsert appends the data as a new record at the end of theyearlySales table.

10 In Microsoft Access, view the yearlySales table to verify the results.

11 Close the cursor.

close(curs);

12 Continue with the next example (“Replacing Existing Database Data withExported Data” on page 4-12). To stop now and resume working with thenext example at a later time, close the connection.

4-10

Page 151: Database Toolbox™ II

Exporting Data to New Record in Database

close(conn);

4-11

Page 152: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Replacing Existing Database Data with Exported DataThis example updates the Month field that you previously imported(“Exporting Data to New Record in Database” on page 4-8) into theyearlySales table of the dbtoolboxdemo data source using the followingDatabase Toolbox functions:

• close

• update

For more information on these functions, seematlab\toolbox\database\dbdemos\dbupdatedemo.m.

1 Change the month in yearlySales table from March to March2010. Assignthe new month value to the newdata cell array.

colnames = {'Month'};newdata = {'March2010'}newdata =

'March2010'

2 Specify the record to update in the database by defining a SQL wherestatement and assigning it to the variable whereclause. The record toupdate is the record whose Month is March. Because the date string iswithin a string, it is embedded within two single quotation marks ratherthan one.

whereclause = 'where Month = ''March'''whereclause =where Month = 'March'

3 Export the data, replacing the record whose Month is March.

update(conn,'yearlySales',colnames,newdata,whereclause)

4 In Microsoft Access, view the yearlySales table to verify the results.

4-12

Page 153: Database Toolbox™ II

Replacing Existing Database Data with Exported Data

5 Disconnect from the database.

close(conn);

4-13

Page 154: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Exporting Multiple Records from the MATLAB WorkspaceThis example does the following:

1 Imports monthly sales figures for all products from the dbtoolboxdemodata source into the MATLAB workspace.

2 Computes total sales for each month.

3 Exports the totals to a new table.

You use the following Database Toolbox functions:

• fastinsert

• setdbprefs

For more information on these functions, seematlab\toolbox\database\dbdemos\dbinsert2demo.m.

1 Ensure that the dbtoolboxdemo data source is writable, that is, not readonly.

2 Use the database function to connect to the data source, assigning thereturned connection object as conn. Pass the following arguments to thisfunction:

• dbtoolboxdemo, the name of the data source

• username and password, which are passed as empty strings because nouser name or password is required to access the database

conn = database('dbtoolboxdemo', '', '');

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

3 Use the setdbprefs function to specify preferences for the retrieved data.Set the data return format to numeric and specify that NULL values readfrom the database are converted to 0 in the MATLAB workspace.

setdbprefs...

4-14

Page 155: Database Toolbox™ II

Exporting Multiple Records from the MATLAB® Workspace

({'NullNumberRead';'DataReturnFormat'},{'0';'numeric'})

When you specify DataReturnFormat as numeric, the value forNullNumberRead must also be numeric.

4 Import data from the salesVolume table.

curs = exec(conn, 'select * from salesVolume');curs = fetch(curs);

5 Use columnnames to view the column names in the fetched data set:

columnnames(curs)ans ='StockNumber', 'January', 'February', 'March', 'April','May', 'June', 'July', 'August', 'September', 'October','November', 'December'

6 View the data for January (column 2).

curs.Data(:,2)ans =

140024001800300043005000120030003000

0

4-15

Page 156: Database Toolbox™ II

4 Using Database Toolbox™ Functions

7 Assign the dimensions of the matrix containing the fetched data set tom and n.

[m,n] = size(curs.Data)m =

10n =

13

8 Use m and n to compute monthly totals. The variable tmp is the salesvolume for all products in a given month c. The variable monthly is thetotal sales volume of all products for that month. For example, if c is 2,row 1 of monthly is the total of all rows in column 2 of curs.Data, wherecolumn 2 is the sales volume for January.

for c = 2:ntmp = curs.Data(:,c);monthly(c-1,1) = sum(tmp(:));

end

View the result.

monthly25100156211460611944996586436525589986321317048345172000

9 Create a string array containing the column names into which you want toinsert the data, and assign the array to the variable colnames.

colnames{1,1} = 'salesTotal';

4-16

Page 157: Database Toolbox™ II

Exporting Multiple Records from the MATLAB® Workspace

10 Use fastinsert to insert the data into the yearlySales table:

fastinsert(conn, 'yearlySales', colnames, monthly)

11 To verify that the data was imported correctly, in Microsoft Access, viewthe yearlySales table from the tutorial database.

12 Close the cursor and the database connection.

close(curs);close(conn);

4-17

Page 158: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Exporting Data Using the Bulk Insert Command

In this section...

“Bulk Insert to Oracle” on page 4-18

“Bulk Insert to Microsoft® SQL Server® 2005” on page 4-20

“Bulk Insert to MySQL” on page 4-22

Bulk Insert to OracleThis example demonstrates how to export data to the Oracle server using thebulk insert command. To follow this example, use a data file on the localmachine where Oracle is installed.

1 Connect to the Oracle database.

javaaddpath 'path\ojdbc5.jar';conn = database('databasename','user','password', ...

'oracle.jdbc.driver.OracleDriver', ...'jdbc:oracle:thin:@machine:port:databasename');

2 Create a table named BULKTEST.

e = exec(conn,['create table BULKTEST (salary number, '...'player varchar2(25), signed varchar2(25), '...'team varchar2(25))']);close(e)

3 Enter data records. A sample record appears as follows.

A = {100000.00,'KGreen','06/22/2011','Challengers'};

4 Expand A to a 10,000-record data set.

A = A(ones(10000,1),:);

5 Write data to a file for bulk insert.

4-18

Page 159: Database Toolbox™ II

Exporting Data Using the Bulk Insert Command

Tip When connecting to a database on a remote machine, you must writethis file to the remote machine. Oracle has problems trying to read filesthat are not on the same machine as the instance of the database.

fid = fopen('c:\temp\tmp.txt','wt');for i = 1:size(A,1)

fprintf(fid,'%10.2f \t %s \t %s \t %s \n',A{i,1}, ...A{i,2},A{i,3},A{i,4});

endfclose(fid);

6 Set the folder location.

e = exec(conn, ...'create or replace directory ext as ''C:\\Temp''');

close(e)

7 Delete the temporary table if it exists.

e = exec(conn,'drop table testinsert');try,close(e),end

8 Create a temporary table and bulk insert it into the table BULKTEST.

e = exec(conn,['create table testinsert (salary number, '...

'player varchar2(25), signed varchar2(25), '...

'team varchar2(25)) organization external '...

'( type oracle_loader default directory ext access '...

'parameters ( records delimited by newline fields '...

'terminated by ''\t'') location (''tmp.txt'')) '...

'reject limit 10000']);

close(e)

e = exec(conn,'insert into BULKTEST select * from testinsert');

close(e)

9 Confirm the number of rows and columns in BULKTEST.

4-19

Page 160: Database Toolbox™ II

4 Using Database Toolbox™ Functions

e = exec(conn, 'select * from BULKTEST');

results = fetch(e)

results =

Attributes: []

Data: {10000x4 cell}

DatabaseObject: [1x1 database]

RowLimit: 0

SQLQuery: 'select * from BULKTEST'

Message: []

Type: 'Database Cursor Object'

ResultSet: [1x1 oracle.jdbc.driver.OracleResultSetImpl]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]

Statement: [1x1 oracle.jdbc.driver.OracleStatementWrapper]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

columnnames(results)

ans =

'SALARY','PLAYER','SIGNED','TEAM'

10 Close the connection.

close(conn)

Bulk Insert to Microsoft SQL Server 2005

1 Connect to the Microsoft SQL Server. For JDBC driver use, add the jarfile to the MATLAB javaclasspath.

javaaddpath 'path\sqljdbc4.jar';conn = database('databasename','user','password', ...

'com.microsoft.sqlserver.jdbc.SQLServerDriver', ...'jdbc:sqlserver://machine:port;database=databasename');

2 Create a table named BULKTEST.

4-20

Page 161: Database Toolbox™ II

Exporting Data Using the Bulk Insert Command

e = exec(conn,['create table BULKTEST (salary '...'decimal(10,2), player varchar(25), signed_date '...'datetime, team varchar(25))']);close(e)

3 Enter data records. A sample record appears as follows.

A = {100000.00,'KGreen','06/22/2011','Challengers'};

4 Expand A to a 10,000-record data set.

A = A(ones(10000,1),:);

5 Write data to a file for bulk insert.

Tip When connecting to a database on a remote machine, you must writethis file to the remote machine. Microsoft SQL Server has problems tryingto read files that are not on the same machine as the instance of thedatabase.

fid = fopen('c:\temp\tmp.txt','wt');for i = 1:size(A,1)

fprintf(fid,'%10.2f \t %s \t %s \t %s \n',A{i,1}, ...A{i,2},A{i,3},A{i,4});

end

6 Run the bulk insert.

e = exec(conn,['bulk insert BULKTEST from '...'''c:\temp\tmp.txt''with (fieldterminator = ''\t'', '...'rowterminator = ''\n'')']);

7 Confirm the number of rows and columns in BULKTEST.

4-21

Page 162: Database Toolbox™ II

4 Using Database Toolbox™ Functions

e = exec(conn, 'select * from BULKTEST');results = fetch(e)

results =

Attributes: []Data: {10000x4 cell}

DatabaseObject: [1x1 database]RowLimit: 0SQLQuery: 'select * from BULKTEST'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 com.microsoft.sqlserver.jdbc.SQLServerResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]Statement: [1x1 com.microsoft.sqlserver.jdbc.SQLServerStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

columnnames(results)

ans =

'salary','player','signed_date','team'

8 Close the connection.

close(conn)

Bulk Insert to MySQL

1 Connect to the MySQL server. For JDBC driver use, add the jar file tothe MATLAB javaclasspath.

javaaddpath 'path\mysql-connector-java-5.1.13-bin.jar';conn = database('databasename', 'user', 'password', ...

'com.mysql.jdbc.Driver', ...'jdbc:mysql://machine:port/databasename');

2 Create a table named BULKTEST.

4-22

Page 163: Database Toolbox™ II

Exporting Data Using the Bulk Insert Command

e = exec(conn,['create table BULKTEST (salary decimal, '...'player varchar(25), signed_date varchar(25), '...'team varchar(25))']);

close(e)

3 Create a data record, such as the one that follows.

A = {100000.00,'KGreen','06/22/2011','Challengers'};

4 Expand A to be a 10,000-record data set.

A = A(ones(10000,1),:);

5 Write data to a file for bulk insert.

Note MySQL reads files saved locally, even if you are connecting to aremote machine.

fid = fopen('c:\temp\tmp.txt','wt');

for i = 1:size(A,1)

fprintf(fid,'%10.2f \t %s \t %s \t %s \n', ...

A{i,1},A{i,2},A{i,3},A{i,4});

end

fclose(fid);

6 Run the bulk insert. Note the use of local infile.

e = exec(conn,['load data local infile '...

' ''C:\\temp\\tmp.txt'' into table BULKTEST '...

'fields terminated by ''\t'' lines terminated '...

'by ''\n''']);

close(e)

7 Confirm the number of rows and columns in BULKTEST.

4-23

Page 164: Database Toolbox™ II

4 Using Database Toolbox™ Functions

e = exec(conn, 'select * from BULKTEST');results = fetch(e)

results =

Attributes: []Data: {10000x4 cell}

DatabaseObject: [1x1 database]RowLimit: 0SQLQuery: 'select * from BULKTEST'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 com.mysql.jdbc.JDBC4ResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]Statement: [1x1 com.mysql.jdbc.StatementImpl]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

columnnames(results)

ans =

'salary','player','signed_date','team'

8 Close the connection.

close(conn)

4-24

Page 165: Database Toolbox™ II

Retrieving Image Data Types

Retrieving Image Data TypesThis example retrieves images from the dbtoolboxdemodata source using a sample file that parses image data,matlabroot/toolbox/database/vqb/parsebinary.m.

1 Connect to the dbtoolboxdemo data source.

conn = database('dbtoolboxdemo', '', '');

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

2 Specify cellarray as the data return format preference.

setdbprefs('DataReturnFormat','cellarray');

3 Import the InvoiceNumber and Receipt columns of data from the Invoicetable.

curs = exec(conn, 'select InvoiceNumber, Receipt from Invoice')curs = fetch(curs);

4 View the data you imported.

curs.Data

ans =

[ 2101] [1948410x1 int8][ 3546] [2059994x1 int8][ 33116] [ 487034x1 int8][ 34155] [2059994x1 int8][ 34267] [2454554x1 int8][ 37197] [1926362x1 int8][ 37281] [2403674x1 int8][ 41011] [1920474x1 int8][ 61178] [2378330x1 int8][ 62145] [ 492314x1 int8][456789] [][987654] []

4-25

Page 166: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Note Some OTHER data type fields may be empty, indicating that the datacould not pass through the JDBC/ODBC bridge.

5 Assign the image element you want to the variable receipt.

receipt = curs.Data{1,2};

6 Run parsebinary. This program writes the retrieved data to a file, stripsODBC header information from it, and displays receipt as a bitmap imagein a figure window. Ensure that your current folder is writable so that theoutput of parsebinary can be written to it.

cd 'I:\MATLABFiles\myfilesparsebinary(receipt, 'BMP');

For more information on parsebinary, enter help parsebinary or view itsfile in the MATLAB Editor/Debugger by entering open parsebinary.

4-26

Page 167: Database Toolbox™ II

Working with Database Metadata

Working with Database Metadata

In this section...

“Accessing Metadata” on page 4-27

“Resultset Metadata Objects” on page 4-33

Accessing MetadataIn this example, you use the following Database Toolbox functions to accessmetadata:

• dmd

• get

• supports

• tables

1 Connect to the dbtoolboxdemo data source.

conn = database('dbtoolboxdemo', '', '')conn =

Instance: 'dbtoolboxdemo'UserName: ''

Driver: []URL: []

Constructor: [1x1 ...com.mathworks.toolbox.database.databaseConnect]

Message: []Handle: [1x1 sun.jdbc.odbc.JdbcOdbcConnection]

TimeOut: 0AutoCommit: 'on'

Type: 'Database Object'

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

2 Use the dmd function to create a database metadata objectdbmeta andreturn its handle, or identifier:

4-27

Page 168: Database Toolbox™ II

4 Using Database Toolbox™ Functions

dbmeta = dmd(conn)

dbmeta = DMDHandle: ...[1x1 sun.jdbc.odbc.JdbcOdbcDatabaseMetaData]

3 Use the get function to assign database properties data, dbmeta, to thevariable v:

v = get(dbmeta)v =

AllProceduresAreCallable: 1AllTablesAreSelectable: 1

DataDefinitionCausesTransactionCommit: 1DataDefinitionIgnoredInTransactions: 0

DoesMaxRowSizeIncludeBlobs: 0Catalogs: {4x1 cell}

CatalogSeparator: '.'CatalogTerm: 'DATABASE'

DatabaseProductName: 'ACCESS'DatabaseProductVersion: '04.00.0000'

DefaultTransactionIsolation: 2DriverMajorVersion: 2DriverMinorVersion: 1

DriverName: [1x31 char]DriverVersion: '2.0001 (04.00.6200)'

ExtraNameCharacters: [1x29 char]IdentifierQuoteString: '`'

IsCatalogAtStart: 1MaxBinaryLiteralLength: 255

MaxCatalogNameLength: 260MaxCharLiteralLength: 255MaxColumnNameLength: 64MaxColumnsInGroupBy: 10

MaxColumnsInIndex: 10MaxColumnsInOrderBy: 10MaxColumnsInSelect: 255MaxColumnsInTable: 255

MaxConnections: 64MaxCursorNameLength: 64

MaxIndexLength: 255

4-28

Page 169: Database Toolbox™ II

Working with Database Metadata

MaxProcedureNameLength: 64MaxRowSize: 4052

MaxSchemaNameLength: 0MaxStatementLength: 65000

MaxStatements: 0MaxTableNameLength: 64MaxTablesInSelect: 16MaxUserNameLength: 0NumericFunctions: [1x73 char]

ProcedureTerm: 'QUERY'Schemas: {}

SchemaTerm: ''SearchStringEscape: '\'

SQLKeywords: [1x461 char]StringFunctions: [1x91 char]

StoresLowerCaseIdentifiers: 0StoresLowerCaseQuotedIdentifiers: 0

StoresMixedCaseIdentifiers: 0StoresMixedCaseQuotedIdentifiers: 1

StoresUpperCaseIdentifiers: 0StoresUpperCaseQuotedIdentifiers: 0

SystemFunctions: ''TableTypes: {13x1 cell}

TimeDateFunctions: [1x111 char]TypeInfo: {16x1 cell}

URL: ...'jdbc:odbc:dbtoolboxdemo'

UserName: 'admin'NullPlusNonNullIsNull: 0

NullsAreSortedAtEnd: 0NullsAreSortedAtStart: 0

NullsAreSortedHigh: 0NullsAreSortedLow: 1

UsesLocalFilePerTable: 0UsesLocalFiles: 1

4-29

Page 170: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Tip For more information about the database metadata propertiesreturned by get, see the methods of the DatabaseMetaData object on theOracle Java Web site:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/DatabaseMetaData.ht

4-30

Page 171: Database Toolbox™ II

Working with Database Metadata

4 Some information is too long to fit in the display area of the field, so thesize of the field data appears instead. The Catalogs element is shown as a4-by-1 cell array. View the Catalog information.

v.Catalogs

ans ='D:\Work\databasetoolboxfiles\tutorial''D:\Work\databasetoolboxfiles\tutorial_copy'

5 Use the supports function to see what properties this database supports:

a = supports(dbmeta)a =

AlterTableWithAddColumn: 1AlterTableWithDropColumn: 1

ANSI92EntryLevelSQL: 1ANSI92FullSQL: 0

ANSI92IntermediateSQL: 0CatalogsInDataManipulation: 1CatalogsInIndexDefinitions: 1

CatalogsInPrivilegeDefinitions: 0CatalogsInProcedureCalls: 0

CatalogsInTableDefinitions: 1ColumnAliasing: 1

Convert: 1CoreSQLGrammar: 0

CorrelatedSubqueries: 1DataDefinitionAndDataManipulationTransactions: 1

DataManipulationTransactionsOnly: 0DifferentTableCorrelationNames: 0

ExpressionsInOrderBy: 1ExtendedSQLGrammar: 0

FullOuterJoins: 0GroupBy: 1

GroupByBeyondSelect: 1GroupByUnrelated: 0

IntegrityEnhancementFacility: 0LikeEscapeClause: 0

LimitedOuterJoins: 0

4-31

Page 172: Database Toolbox™ II

4 Using Database Toolbox™ Functions

MinimumSQLGrammar: 1MixedCaseIdentifiers: 1

MixedCaseQuotedIdentifiers: 0MultipleResultSets: 0

MultipleTransactions: 1NonNullableColumns: 0

OpenCursorsAcrossCommit: 0OpenCursorsAcrossRollback: 0

OpenStatementsAcrossCommit: 1OpenStatementsAcrossRollback: 1

OrderByUnrelated: 0OuterJoins: 1

PositionedDelete: 0PositionedUpdate: 0

SchemasInDataManipulation: 0SchemasInIndexDefinitions: 0

SchemasInPrivilegeDefinitions: 0SchemasInProcedureCalls: 0

SchemasInTableDefinitions: 0SelectForUpdate: 0

StoredProcedures: 1SubqueriesInComparisons: 1

SubqueriesInExists: 1SubqueriesInIns: 1

SubqueriesInQuantifieds: 1TableCorrelationNames: 1

Transactions: 1Union: 1

UnionAll: 1

A 1 for a given property indicates that the database supports that property;a 0 means that the database does not support the property.

Tip For more information about properties that the database supports, seethe methods of the DatabaseMetaData object on the Oracle Java Web site athttp://docs.oracle.com/javase/1.4.2/docs/api/java/sql/DatabaseMetaData.ht

4-32

Page 173: Database Toolbox™ II

Working with Database Metadata

6 Alternatively, use the tables function to retrieve metadata, such as thenames and types of the tables in a catalog in the database. Pass thefollowing arguments to this function:

• dbmeta, the name of the database metadata object.

• tutorial, the name of the catalog from which you want to retrieve tablenames.

t = tables(dbmeta, 'tutorial')t =

'MSysAccessObjects' 'SYSTEM TABLE''MSysIMEXColumns' 'SYSTEM TABLE''MSysIMEXSpecs' 'SYSTEM TABLE''MSysObjects' 'SYSTEM TABLE''MSysQueries' 'SYSTEM TABLE''MSysRelationships' 'SYSTEM TABLE''inventoryTable' 'TABLE''productTable' 'TABLE''salesVolume' 'TABLE''suppliers' 'TABLE''yearlySales' 'TABLE''display' 'VIEW'

7 Close the database connection.

close(conn)

Resultset Metadata ObjectsUse the resultset function to create resultset objects for cursor object. Then,use the rsmd function to get metadata information about the resultset objects.

For more information, see the resultset and rsmd function reference pages.

4-33

Page 174: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Using Driver FunctionsThis example uses the following Database Toolbox functions to create driverand drivermanager objects, and to get and set their properties:

• driver

• drivermanager

• get

• isdriver

• set

Note There is no equivalent MATLAB example available because thisexample relies on a specific system-to-JDBC connection and database. Yourconfiguration is different from the one in this example, so you cannot runthese examples exactly as written. Instead, substitute appropriate values foryour own system. See your database administrator for more information.

1 Connect to the database.

c = database('orc1','scott','tiger',...'oracle.jdbc.driver.OracleDriver',...'jdbc:oracle:thin:@144.212.123.24:1822:');

2 Use the driver function to construct a driver object and returnits handle, for a specified database URL string of the formjdbc:subprotocol:subname.

d = driver('jdbc:oracle:thin:@144.212.123.24:1822:')DriverHandle: [1x1 oracle.jdbc.driver.OracleDriver]

3 Use the get function to get information, such as version data, for thedriver object.

v = get(d)v =MajorVersion: 1

4-34

Page 175: Database Toolbox™ II

Using Driver Functions

MinorVersion: 0

4 Use isdriver to verify that d is a valid JDBC driver object.

isdriver(d)ans =1

This result shows that d is a valid JDBC driver object. If it is a not validJDBC driver object, the returned result is 0.

5 Use the drivermanager function to create a drivermanager object dm.

dm = drivermanager

6 Get properties of the drivermanager object.

v = get(dm)v =

Drivers: {'sun.jdbc.odbc.JdbcOdbcDriver@761630' ...[1x38 char]}

LoginTimeout: 0LogStream: []

7 Set the LoginTimeout value to 10 for all drivers loaded during this session.

set(dm,'LoginTimeout',10)

Verify the LoginTimeout value.

v = get(dm)v =

Drivers: {'sun.jdbc.odbc.JdbcOdbcDriver@761630'}LoginTimeout: 10

LogStream: []

4-35

Page 176: Database Toolbox™ II

4 Using Database Toolbox™ Functions

About Database Toolbox Objects and MethodsThis toolbox is an object-oriented application. You do not need to be familiarwith the product’s object-oriented implementation to use it; this informationis provided for reference purposes.

Database Toolbox software includes the following objects:

• Cursor

• Database

• Database metadata

• Driver

• Drivermanager

• Resultset

• Resultset metadata

Each object has its own method folder, whose name begins with an @ sign, inthe matlabroot/toolbox/database/database folder. Functions in the folderfor each object provide methods for operating on the object.

Object-oriented characteristics of the toolbox enable you to:

• Use constructor functions to create and return information about objects.

For example, to create a cursor object containing query results, run thefetch function. The object and stored information about the object arereturned. Because objects are MATLAB structures, you can view elementsof the returned object.

4-36

Page 177: Database Toolbox™ II

About Database Toolbox™ Objects and Methods

This example uses the fetch function to create a cursor object curs.

curs = exec(conn, 'select productdescription from producttable');

curs = fetch(curs)

curs =

Attributes: []

Data: {10x1 cell}

DatabaseObject: [1x1 database]

RowLimit: 0

SQLQuery: 'select productdescription from producttable'

Message: []

Type: 'Database Cursor Object'

ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]

Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

View the contents of the Data element in the cursor object.

curs.Data

ans =

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

• Use overloaded functions.

Objects allow the use of overloaded functions, which simplify usage becauseyou only need to use one function to operate on objects.For example, usethe get function to view properties of an object.

4-37

Page 178: Database Toolbox™ II

4 Using Database Toolbox™ Functions

• Create custom methods that operate on Database Toolbox objects and storethem in the MATLAB workspace.

4-38

Page 179: Database Toolbox™ II

Using the exec Function

Using the exec Function

In this section...

“About the exec Function” on page 4-39

“Using Cursor Objects” on page 4-39

“Working with Microsoft® Excel®” on page 4-40

“Database Considerations” on page 4-40

About the exec FunctionUse the exec function to execute an SQL statement and return the databasecursor object. Here are some general points about using exec:

• Use Database Explorer to query databases as an alternative to using exec.

• exec supports the native ODBC interface.

• Unless noted in this reference page, the exec function supports all validSQL statements, such as nested queries.

• The sqlquery argument can be a stored procedure for the databaseconnection of the form {call sp_name (parm1,parm2,...)}.

• Use exec when the stored procedure returns one or more result sets. Forprocedures that return output parameters, use runstoredprocedure.

Using Cursor Objects

• Check curs.Message to find any error messages returned from thedatabase after query execution. If you would like the error messages to bethrown to the MATLAB command prompt, use setdbprefs as follows.

setdbprefs('Errorhandling','report');

curs = exec(conn,'select * invalidtablename')

To store error messages in curs.Message instead of sending them to theMATLAB command prompt, use setdbprefs as follows.

setdbprefs('Errorhandling','store');

4-39

Page 180: Database Toolbox™ II

4 Using Database Toolbox™ Functions

• After opening a cursor, use fetch to import data from the cursor. Useresultset, rsmd, and access the Statement property to get properties ofthe cursor.

• You can have multiple cursors open at one time.

• A cursor stays open until you close it using the close function.

Working with Microsoft ExcelFor Microsoft Excel, tables in sqlquery are Excel worksheets. By default,some worksheet names include $. To select data from a worksheet with thisname format, use a SQL statement of the form select * from "Sheet1$"(or 'Sheet1$') .

Database Considerations

• The order of records in your database is not constant. Use values in columnnames to identify records. Use the SQL ORDER BY command to sort records.

• Before you modify database tables, ensure that the database is not openfor editing. If you try to edit the database while it is open, you receivethis MATLAB error:

[Vendor][ODBC Driver] The database engine could not locktable 'TableName' because it is already in use byanother person or process.

• You might experience issues with text field formats in the Microsoft SQLServer database management system. Workarounds for these issues are asfollows:

- Convert fields of format NVARCHAR, TEXT, NTEXT, and VARCHAR to CHARin the database.

- Use sqlquery to convert data to VARCHAR. For example, run a sqlquerystatement of the form 'select convert(varchar(20),field1) fromtable1'.

• The PostgreSQL database management system supports multidimensionalfields, but SQL select statements fail when retrieving these fields unlessyou specify an index.

4-40

Page 181: Database Toolbox™ II

Using the exec Function

• Some databases require that you include a symbol, such as #, before andafter a date in a query as follows:

curs = exec(conn,'select * from mydb where mydate > #03/05/2005#')

• Some databases require that you include a symbol, such as #, before andafter a date in a query as follows:

curs = exec(conn,'select * from mydb where mydate > #03/05/2005#')

4-41

Page 182: Database Toolbox™ II

4 Using Database Toolbox™ Functions

Using the fetch Function

In this section...

“About the fetch Function” on page 4-42

“fetch Workflow” on page 4-42

“Using fetch with a Cursor Object” on page 4-43

“Database Considerations” on page 4-44

About the fetch FunctionUse the fetch function to import data into the MATLAB workspace. Here aresome general points about using fetch:

• Use Database Explorer to retrieve data as an alternative to using fetch.

• fetch supports the native ODBC interface.

fetch WorkflowThe fetch function runs the appropriate processes to retrieve data dependingon what object you provide to it as an input argument. This function workswith cursor objects and database connection objects for ODBC/JDBC bridgeand JDBC interfaces. This function works with cursor objects only for thenative ODBC interface.

For the JDBC database driver, use the database function to establish adatabase connection.

conn = database(...)

Then, fetch runs when you pass a cursor object, curs, to retrieve as anargument.

curs = exec(conn,sqlquery)curs = fetch(curs)

The fetch function runs when you pass a database object, conn, to retrieveas an argument.

4-42

Page 183: Database Toolbox™ II

Using the fetch Function

fetch(conn,sqlquery)

Note You can pass conn as an input argument to fetch when you are usingan ODBC/JDBC bridge or a JDBC interface. For the native ODBC interface,use curs as the input argument.

To create a database connection using the native ODBC interface, usedatabase.ODBCConnection.

conn = database.ODBCConnection(...)

Then, the fetch function runs when you pass a native ODBC cursor object,curs, to retrieve as an argument.

curs = exec(conn,sqlquery)curs = fetch(curs)

When fetch returns a cursor object, you can run many other functions,such as get and rows. To import data into the MATLAB workspace withoutmetadata, use fetch with a database connection object as the input argument.

Using fetch with a Cursor Object

• fetch returns data stored in a MATLAB cell array, table, dataset,structure, or numeric matrix.

• When working with a JDBC or JDBC/ODBC bridge connection establishedusing database, running fetch on the cursor object returns a new object oftype cursor which points to the same underlying Java objects as the inputcursor. It is therefore best practice to overwrite the input cursor object.This practice results in only one open cursor object, which consumes lessmemory than multiple open cursor objects.

curs = fetch(curs)

After this, you simply need to close this one object. Creating a differentvariable for the output cursor object will unnecessarily create two objectspointing to the same underlying Java statement and result set objects.

4-43

Page 184: Database Toolbox™ II

4 Using Database Toolbox™ Functions

With a native ODBC connection established usingdatabase.ODBCConnection, running fetch on the cursor object updatesthe input cursor object itself. Depending on whether or not you provide anoutput argument, the same object gets copied over to the output. Thus,there is always only one cursor object created in memory for any of thefollowing usages:

curs = fetch(curs)fetch(curs)curs2 = fetch(curs)

• The next time fetch is run, records are imported starting with the rowfollowing the specified number of rows in rowlimit. If you specify a rowlimit of 0, all the rows of data are fetched.

• Fetching large amounts of data can result in memory or speed issues. Userowlimit to limit how much data you retrieve at once.

• If 'FetchInBatches' is set to 'yes' in the preferences using setdbprefs,fetch incrementally fetches the number of rows specified in the'FetchBatchSize' setting until all the rows returned by the query arefetched, or until the limited number of rows are fetched, if rowlimit isspecified. Use this method when fetching a large number of rows fromthe database.

Caution: Leaving cursor and connection objects open or overwriting openobjects can result in unexpected behavior. Once you finish working with theseobjects, you must close them using close.

Database Considerations

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

4-44

Page 185: Database Toolbox™ II

5

Functions — AlphabeticalList

Page 186: Database Toolbox™ II

attr

Purpose Retrieve attributes of columns in fetched data set

Syntax attributes = attr(curs, colnum)attributes = attr(curs)

Description attributes = attr(curs, colnum) retrieves attribute information forthe column number colnum in the fetched data set curs.

attributes = attr(curs) retrieves attribute information for allcolumns in the fetched data set curs and stores the data in a cell array.

attributes = attr(colnum) displays attributes of column colnum.

A list of returned attributes appears in the following table.

Attribute Description

fieldName Name of the column.

typeName Data type.

typeValue Numerical representation of the data type.

columnWidth Size of the field.

precision Precision value for floating and double datatypes; an empty value is returned for strings.

scale Precision value for real and numeric datatypes; an empty value is returned for strings.

currency If true, data format is currency.

readOnly If true, data cannot be overwritten.

nullable If true, data can be NULL.

Message Error message returned by fetch.

Examples Example 1 — Get Attributes for One Column

Get column attributes for the fourth column of a fetched data set:

attr(curs, 4)

5-2

Page 187: Database Toolbox™ II

attr

ans =fieldName: 'Age'typeName: 'LONG'

typeValue: 4columnWidth: 11

precision: []scale: []

currency: 'false'readOnly: 'false'nullable: 'true'Message: []

Example 2 — Get Attributes for All Columns

1 Get column attributes for curs and assign them to attributes.

attributes = attr(curs)

2 View the attributes of column 4.

attributes(4)ans =

fieldName: 'Age'typeName: 'LONG'

typeValue: 4columnWidth: 11

precision: []scale: []

currency: 'false'readOnly: 'false'nullable: 'true'Message: []

See Also cols | columnnames | columns | fetch | dmd | get | tables | width

5-3

Page 188: Database Toolbox™ II

bestrowid

Purpose Unique identifier for row in database table

Syntax b = bestrowid(dbmeta,'cata','sch')b = bestrowid(dbmeta,'cata','sch','tab')

Description b = bestrowid(dbmeta,'cata','sch') returns the optimal set ofcolumns in a table that uniquely identifies a row in the schema sch, inthe catalog cata, for the database whose database metadata object isdbmeta.

b = bestrowid(dbmeta,'cata','sch','tab') returns the optimal setof columns that uniquely identifies a row in table tab, in the schemasch, in the catalog cata, for the database whose database metadataobject is dbmeta.

Examples Run bestrowid, passing it the following arguments:

• dbmeta, the database metadata object

• msdb, the catalog

• geck, the schema

• builds, the tableb = bestrowid(dbmeta, 'msdb', 'geck', 'builds')b =

'build_id'

The result indicates that each entry in the build_id column is uniqueand identifies the row.

See Also columns | dmd | get | tables

5-4

Page 189: Database Toolbox™ II

clearwarnings

Purpose Clear warnings for database connection or resultset

Syntax clearwarnings(conn)clearwarnings(rset)

Description clearwarnings(conn) clears warnings reported for the databaseconnection object conn.

clearwarnings(rset) clears warnings reported for the resultsetobject rset.

Tip For command-line help on clearwarnings, use the overloadedmethods:

help database/clearwarningshelp resultset/clearwarnings

See Also database | get | resultset

5-5

Page 190: Database Toolbox™ II

close

Purpose Close database connection, cursor, or resultset object

Syntax close(object)

Description close(object) closes object, which frees up resources.

Allowable objects for close are listed in the following table.

Object Description Action Performed byclose (object)

conn Database connectionobject or native ODBCdatabase connectionobject

Closes conn

curs Cursor object or nativeODBC cursor object

Closes curs

rset Resultset object Closes rset

Database connections, cursors, and resultset objects remain openuntil you close them using the close function. Always close a cursor,connection, or resultset when you finish using it. Close a cursor beforeclosing the connection used for that cursor.

Note The MATLAB session closes open cursors and connections whenexiting, but the database might not free up the cursors and connections.

5-6

Page 191: Database Toolbox™ II

close

Tip For command-line help on close, use the overloaded methods:

help database/closehelp cursor/closehelp resultset/close

Examples Close the cursor curs and the connection conn.

close(curs);close(conn);

See Also fetch | database | exec | resultset

5-7

Page 192: Database Toolbox™ II

cols

Purpose Retrieve number of columns in fetched data set

Syntax numcols = cols(curs)

Description numcols = cols(curs) returns the number of columns in the fetcheddata set curs.

Examples Display three columns in the fetched data set curs.

numcols = cols(curs)

numcols =3

See Also attr | columnnames | columnprivileges | columns | fetch | get| rows | width

How To • “Using the Native ODBC Database Connection” on page 2-12

5-8

Page 193: Database Toolbox™ II

columnnames

Purpose Retrieve names of columns in fetched data set

Syntax FIELDSTRING = columnnames(CURSOR)FIELDSTRING = columnnames(CURSOR,BCELLARRAY)

Description FIELDSTRING = columnnames(CURSOR) returns the column names ofthe data selected from a database table. The column names are enclosedin quotes and separated by commas. (The columnnames function is notsupported for a cursor object returned by the fetchmulti function.)

FIELDSTRING = columnnames(CURSOR,BCELLARRAY) returns thecolumn names as a cell array of strings when BCELLARRAY is set to true.

Examples 1 Run a SQL query to return all columns from the Microsoft Accessdbtoolboxdemo data source database suppliers table:

sql = 'select * from suppliers'cursor = exec(connection, sql)cursor = fetch(cursor)

2 Use columnnames to retrieve all column names for the selectedcolumns:

fieldString = columnnames(cursor)fieldString ='SupplierNumber','SupplierName','City','Country','FaxNumber'

See Also attr | cols | columnprivileges | columns | fetch | get | width

5-9

Page 194: Database Toolbox™ II

columnprivileges

Purpose List database column privileges

Syntax lp = columnprivileges(dbmeta,'cata','sch','tab')lp = columnprivileges(dbmeta,'cata','sch','tab','l')

Description lp = columnprivileges(dbmeta,'cata','sch','tab') returns a listof privileges for all columns in the table tab, in the schema sch, inthe catalog cata for the database whose database metadata object isdbmeta.

lp = columnprivileges(dbmeta,'cata','sch','tab','l') returnsa list of privileges for column l in the table tab, in the schema sch, inthe catalog cata for the database whose database metadata object isdbmeta.

Examples Return a list of privileges for the given database, catalog, schema, table,and column name:

lp = columnprivileges(dbmeta,'msdb','geck','builds',...'build_id')lp =

'builds' 'build_id' {1x4 cell}

View the contents of the third column in lp:

lp{1,3}ans =

'INSERT' 'REFERENCES' 'SELECT' 'UPDATE'

See Also cols | columns | columnnames | dmd | get

5-10

Page 195: Database Toolbox™ II

columns

Purpose Return database table column names

Syntax l = columns(dbmeta, 'cata')l = columns(dbmeta, 'cata', 'sch')l = columns(dbmeta, 'cata', 'sch', 'tab')

Description l = columns(dbmeta, 'cata') returns a list of all column names inthe catalog cata for the database whose database metadata object isdbmeta.

l = columns(dbmeta, 'cata', 'sch') returns a list of all columnnames in the schema sch.

l = columns(dbmeta, 'cata', 'sch', 'tab') returns a list ofcolumns for the table tab.

Examples 1 Run columns for the arguments shown:

l = columns(dbmeta,'orcl', 'SCOTT')l =

'BONUS' {1x4 cell}'DEPT' {1x3 cell}'EMP' {1x8 cell}'SALGRADE' {1x3 cell}'TRIAL' {1x3 cell}

The results show the names of the five tables in dbmeta, and cellarrays containing the column names in each table.

2 View the column names for the BONUS table:

l{1,2}ans =

'ENAME' 'JOB' 'SAL' 'COMM'

See Also attr | bestrowid | cols | columnnames | columnprivileges | dmd| get | versioncolumns

5-11

Page 196: Database Toolbox™ II

commit

Purpose Make database changes permanent

Syntax commit(conn)

Description commit(conn) makes permanent changes made to the databaseconnection conn since the last commit or rollback function was run. Torun this function, the AutoCommit flag for conn must be off.

Examples Example 1 — Check the Status of the Autocommit Flag

Check that the status of the AutoCommit flag for connection conn is off.

get(conn,'AutoCommit')ans =off

Example 2 — Commit Data to a Database

1 Insert exdata into the columns DEPTNO, DNAME, and LOC in the tableDEPT, for the data source conn.

fastinsert(conn, 'DEPT', {'DEPTNO';'DNAME';'LOC'},...exdata)

2 Commit this data.

commit(conn)

See Also database | exec | fastinsert | get | rollback | update

5-12

Page 197: Database Toolbox™ II

confds

Purpose Configure JDBC data source for Visual Query Builder

Alternatives Select Define JDBC data sources from the Visual Query BuilderQuery menu.

Syntax confds

Description confds displays the VQB Define JDBC data sources dialog box. Useconfds only to build and run queries using Visual Query Builder withJDBC drivers.

For information about how to use the Define JDBC data sources dialogbox to configure JDBC drivers, see “Configure JDBC Data Sources”.

Tip Use the database function to define JDBC data sourcesprogrammatically.

See Also database | querybuilder

5-13

Page 198: Database Toolbox™ II

crossreference

Purpose Retrieve information about primary and foreign keys

Syntax f = crossreference(dbmeta, 'pcata', 'psch', 'ptab', 'fcata',

'fsch', 'ftab')

Description f = crossreference(dbmeta, 'pcata', 'psch', 'ptab','fcata', 'fsch', 'ftab') returns information about the relationshipbetween foreign keys and primary keys for the database whose databasemetadata object is dbmeta. The primary key information is for the tableptab in the primary schema psch. The primary catalog is pcata. Theforeign key information is for the foreign table ftab in the foreignschema fsch. The foreign catalog is fcata.

Examples Run crossreference to get primary and foreign key information. Thedatabase metadata object is dbmeta, the primary and foreign catalog isorcl, the primary and foreign schema is SCOTT, the table that containsthe referenced primary key is DEPT, and the table that contains theforeign key is EMP.

f = crossreference(dbmeta,'orcl','SCOTT','DEPT',...'orcl','SCOTT','EMP')

f = Columns 1 through 7'orcl' 'SCOTT' 'DEPT' 'DEPTNO' 'orcl' ...'SCOTT' 'EMP'

Columns 8 through 13'DEPTNO' '1' 'null' '1' 'FK_DEPTNO'...'PK_DEPT'

The results show the following primary and foreign key information.

Column Description Value

1 Catalog that contains primary key,referenced by foreign imported key

orcl

2 Schema that contains primary key,referenced by foreign imported key

SCOTT

5-14

Page 199: Database Toolbox™ II

crossreference

Column Description Value

3 Table that contains primary key,referenced by foreign imported key

DEPT

4 Column name of primary key,referenced by foreign imported key

DEPTNO

5 Catalog that has foreign key orcl

6 Schema that has foreign key SCOTT

7 Table that has foreign key EMP

8 Foreign key column name thatreferences the primary key in anothertable

DEPTNO

9 Sequence number within foreign key 1

10 Update rule, that is, what happens tothe foreign key when the primary keyupdates

null

11 Delete rule, that is, what happens tothe foreign key when the primary keyis deleted

1

12 Foreign imported key name FK_DEPTNO

13 Primary key name in referenced table PK_DEPT

There is only one foreign key in the schema SCOTT. The table DEPTcontains a primary key DEPTNO that is referenced by the field DEPTNO inthe table EMP. The field DEPTNO in the EMP table is a foreign key.

Tip For a description of the codes for update and delete rules, see thegetCrossReference property on the Oracle Java Web site:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/DatabaseMetaData

5-15

Page 200: Database Toolbox™ II

crossreference

See Also dmd | exportedkeys | get | importedkeys | primarykeys

5-16

Page 201: Database Toolbox™ II

cursor.fetch

Purpose Import data into MATLAB Workspace from cursor object created byexec

Alternatives Retrieve data using Database Explorer (dexplore).

Syntax curs = fetch(curs,rowLimit)curs = fetch(curs)

Description curs = fetch(curs,rowLimit) imports rows of data into the objectcurs from the open SQL cursor curs, up to the maximum rowLimit.

curs = fetch(curs) imports rows of data from the open SQL cursorcurs into the object curs, up to rowLimit. Use the set function tospecify rowLimit.

Data is stored in a MATLAB cell array, table, dataset, structure, ornumeric matrix. It is a best practice to assign the object returned byfetch to the variable curs from the open SQL cursor. This practiceresults in only one open cursor object, which consumes less memorythan multiple open cursor objects.

The next time fetch is run, records are imported starting with the rowfollowing the specified rowLimit. If you specify a rowLimit of 0, all therows in the resultset are fetched.

If 'FetchInBatches' is set to 'yes' in the preferences usingsetdbprefs, cursor.fetch incrementally fetches the number of rowsspecified in the 'FetchBatchSize' setting until all the rows returnedby the query are fetched, or until rowLimit number of rows are fetched,if rowLimit is specified. Use this method when fetching a large numberof rows from the database.

Fetching large amounts of data can result in memory or speed issues.In this case, use rowLimit to limit how much data you retrieve at once.

5-17

Page 202: Database Toolbox™ II

cursor.fetch

Caution: Leaving cursor and connection objects open or overwritingopen objects can result in unexpected behavior. Once you are finishedworking with these objects, you must close them using close.

Tips • This page documents fetch for a cursor object. For more informationabout using fetch, cursor.fetch, and database.fetch, see fetch.Unless otherwise noted, fetch in this documentation refers tocursor.fetch, rather than database.fetch.

• cursor.fetch now supports the native ODBC interface.

Examples Import All Rows of Data Using the Native ODBC Interface

Create a connection conn using the native ODBC interface and thedbtoolboxdemo data source.

conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')

conn =

ODBCConnection with properties:

Instance: 'dbtoolboxdemo'UserName: 'admin'Message: []Handle: [1x1 database.internal.ODBCConnectHandle]

TimeOut: 0AutoCommit: 0

Type: 'ODBCConnection Object'

conn has an empty Message property, which means a successfulconnection.

Use fetch to import all data into the database.ODBCCursor object,curs, and store the data in a cell array contained in the cursor objectfield curs.Data.

5-18

Page 203: Database Toolbox™ II

cursor.fetch

curs = exec(conn,'select productDescription from productTable');

curs = fetch(curs)

curs =

ODBCCursor with properties:

Data: {10x1 cell}

RowLimit: 0

SQLQuery: 'select productDescription from productTable'

Message: []

Type: 'ODBCCursor Object'

Statement: [1x1 database.internal.ODBCStatementHandle]

With the native ODBC interface, curs returns an ODBCCursor Objectinstead of a Database Cursor Object.

View the contents of the Data element in the cursor object.

curs.Data

ans =

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

Close the cursor object.

close(curs);

5-19

Page 204: Database Toolbox™ II

cursor.fetch

Import All Rows of Data

Working with the dbtoolboxdemo data source, use exec to select datain column City, for example, in table suppliers. Then, use fetch toimport all data from the SQL statement into the cursor object curs,and store the data in a cell array contained in the cursor object fieldcurs.Data.

curs = exec(conn,'select City from suppliers');

curs = fetch(curs)

curs =

Attributes: []

Data: {10x1 cell}

DatabaseObject: [1x1 database]

RowLimit: 0

SQLQuery: 'select City from suppliers'

Message: []

Type: 'Database Cursor Object'

ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]

Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

View the contents of the Data element in the cursor object.

curs.Data

ans =

'New York''London''Adelaide''Dublin''Boston''New York''Wellesley'

5-20

Page 205: Database Toolbox™ II

cursor.fetch

'Nashua''London''Belfast'

Close the cursor object.

close(curs);

Import a Specified Number of Rows

Working with the dbtoolboxdemo data source, use the rowLimitargument to retrieve only the first three rows of data.

curs = exec(conn,'select productdescription from producttable');curs = fetch(curs,3)

curs =

Attributes: []Data: {3x1 cell}

DatabaseObject: [1x1 database]RowLimit: 0SQLQuery: 'select productdescription from producttable'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

View the data.

curs.Data

ans =

'Victorian Doll''Train Set''Engine Kit'

5-21

Page 206: Database Toolbox™ II

cursor.fetch

Rerun the fetch function to return the second three rows of data.

curs = fetch(curs,3);

View the data.

curs.Data

ans =

'Painting Set''Space Cruiser''Building Blocks'

Close the cursor object.

close(curs);

Import Rows Iteratively Until You Retrieve All Data

Working with the dbtoolboxdemo data source, use the rowLimitargument to retrieve the first two rows of data, and then rerun theimport using a while loop, retrieving two rows at a time. Continue untilyou have retrieved all data, which occurs when curs.Data is 'No Data'.

curs = exec(conn,'select productdescription from producttable');% Initialize rowLimitrowLimit = 2% Check for more data. Retrieve and display all data.while ~strcmp(curs.Data,'No Data')curs=fetch(curs,rowLimit);curs.Data(:)

end

rowLimit =

2

5-22

Page 207: Database Toolbox™ II

cursor.fetch

ans =

'Victorian Doll''Train Set'

ans =

'Engine Kit''Painting Set'

ans =

'Space Cruiser''Building Blocks'

ans =

'Tin Soldier''Sail Boat'

ans =

'Slinky''Teddy Bear'

ans ='No Data'

Close the cursor object.

close(curs);

5-23

Page 208: Database Toolbox™ II

cursor.fetch

Import Numeric Data

Working with the dbtoolboxdemo data source, import a column ofnumeric data, using the setdbprefs function to specify numeric asthe format for the retrieved data.

curs = exec(conn,'select unitCost from productTable');setdbprefs('DataReturnFormat','numeric')curs = fetch(curs,3);curs.Data

ans =

135

16

Close the cursor object.

close(curs);

Import BOOLEAN Data

Import data that includes a BOOLEAN field, using the setdbprefsfunction to specify cellarray as the format for the retrieved data.

curs = exec(conn,['select InvoiceNumber, '...'Paid from Invoice']);setdbprefs('DataReturnFormat','cellarray')curs = fetch(curs,5);A = curs.Data

A =

[ 2101] [0][ 3546] [1][33116] [1][34155] [0][34267] [1]

5-24

Page 209: Database Toolbox™ II

cursor.fetch

View the class of the second column of A.

class(A{1,2})

ans =logical

Close the cursor object.

close(curs);

Perform Incremental Fetch

Working with the dbtoolboxdemo data source, retrieve dataincrementally to avoid Java heap errors. Use cursor.fetch with thesetdbprefs properties for FetchInBatches and FetchBatchSize tofetch large data sets.

setdbprefs('FetchInBatches','yes');setdbprefs('FetchBatchSize','2');conn = database('dbtoolboxdemo','','');curs = exec(conn,'select * from productTable');curs = fetch(curs);A = curs.Data

A =

[ 9] [125970] [1003] [13] 'Victorian Doll'[ 8] [212569] [1001] [ 5] 'Train Set'[ 7] [389123] [1007] [16] 'Engine Kit'[ 2] [400314] [1002] [ 9] 'Painting Set'[ 4] [400339] [1008] [21] 'Space Cruiser'[ 1] [400345] [1001] [14] 'Building Blocks'[ 5] [400455] [1005] [ 3] 'Tin Soldier'[ 6] [400876] [1004] [ 8] 'Sail Boat'[ 3] [400999] [1009] [17] 'Slinky'[10] [888652] [1006] [24] 'Teddy Bear'

5-25

Page 210: Database Toolbox™ II

cursor.fetch

cursor.fetch internally retrieves data in increments of two rows ata time. Tune the FetchBatchSize setting depending on the size ofthe result set you expect to fetch. For example, if you expect about a100,000 rows in the output, a batch size of 10,000 is a good startingpoint. The larger the FetchBatchSize value, the fewer trips betweenJava and MATLAB, and the memory consumption is greater for eachbatch. The optimal value for FetchBatchSize is decided based onseveral factors like the size per row being retrieved, the Java heapmemory value, the driver’s default fetch size, and system architecture,and hence, can vary from site to site.

If 'FetchInBatches' is set to 'yes' and the total number of rowsfetched is less than 'FetchBatchSize', MATLAB shows a warningmessage and then fetches all the rows. The message is Batch sizespecified was larger than the number of rows fetched.

You can exercise a row limit on the final output even when theFetchInBatches setting is 'yes'.

setdbprefs('FetchInBatches','yes');setdbprefs('FetchBatchSize','2');curs = exec(conn,'select * from productTable');curs = fetch(curs,3);A = curs.Data

A =

[9] [125970] [1003] [13] 'Victorian Doll'[8] [212569] [1001] [ 5] 'Train Set'[7] [389123] [1007] [16] 'Engine Kit'

In this case, cursor.fetch retrieves the first three rows ofproductTable, two rows at a time.

Close the cursor object.

close(curs);

5-26

Page 211: Database Toolbox™ II

cursor.fetch

See Also attr | cols | columnnames | database | database.fetch | exec |fetch | fetchmulti | get | logical | rows | resultset | set | width

Tutorials • “Getting Started with Visual Query Builder” on page 3-2

• “Preference Settings for Large Data Import” on page 3-10

How To • “Working with Visual Query Builder”

• “Retrieving BINARY and OTHER Data Types” on page 3-51

• “Using the Native ODBC Database Connection” on page 2-12

5-27

Page 212: Database Toolbox™ II

database

Purpose Connect to database

Syntax conn = database(instance,username,password)conn = database.ODBCConnection(instance,username,password)

conn = database(instance,username,password,driver,databaseurl)

conn = database(instance,username,password,Name,Value)

Description conn = database(instance,username,password) returns a databaseconnection object for the connection to the ODBC data source setup,instance, via an ODBC driver.

conn = database.ODBCConnection(instance,username,password)returns a database connection object for the connection to the ODBCdata source setup, instance, via a native ODBC interface.

conn = database(instance,username,password,driver,databaseurl) connects to the database, instance, via a JDBC driver.

conn = database(instance,username,password,Name,Value)connects to the database, instance, via JDBC driver with connectionproperties specified by one or more Name,Value pair arguments.

InputArguments

instance - Data source setup or database namestring

Data source setup or database name, specified as a string. Specify adata source for ODBC connection, and the database name for JDBCconnection.

username - User namestring

5-28

Page 213: Database Toolbox™ II

database

User name required to access the database, specified as a string. If nouser name is required, specify empty strings, ''.

password - Passwordstring

Password required to access the database, specified as a string. If nopassword is required, specify empty strings, ''.

driver - JDBC driver namestring

JDBC driver name, specified as a string. This is the name of the Javadriver that implements the java.sql.Driver interface. It is part of theJDBC driver name and database connection URL.

databaseurl - Database connection URLstring

Database connection URL, specified as a string. This is a vendor-specificURL that is typically constructed using connection properties likeserver name, port number, database name, and so on. It is part of theJDBC driver name and database connection URL. If you do not knowthe driver name or the URL, you can use name-value pair arguments tospecify individual connection properties.

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments.Name is the argument name and Value is the correspondingvalue. Name must appear inside single quotes (' '). You canspecify several name and value pair arguments in any order asName1,Value1,...,NameN,ValueN.

Example: 'Vendor','MySQL','Server','remotehost' connects to aMySQL database on a machine named remotehost.

’Vendor’ - Database vendor'MySQL' | 'Oracle' | 'Microsoft SQL Server' | 'PostGreSQL'

5-29

Page 214: Database Toolbox™ II

database

Database vendor, specified as the comma-separated pair consisting of'Vendor' and one of the following strings:

• 'MySQL'

• 'Oracle'

• 'Microsoft SQL Server'

• 'PostGreSQL'

If connecting to a database system not listed here, use the driver anddatabaseurl syntax.

Example: 'Vendor','Oracle'

’Server’ - Database server'localhost' (default) | string

Database server name or address, specified as the comma-separatedpair consisting of 'Server' and a string value.

Example: 'Server','remotehost'

’PortNumber’ - Server portscalar

Server port number that the server is listening on, specified as thecomma-separated pair consisting of 'PortNumber' and a scalar value.

Example: 'PortNumber',1234

Data Typesdouble

’AuthType’ - Authentication'Server' (default) | 'Windows'

Authentication type (valid only for Microsoft SQL Server), specifiedas the comma-separated pair consisting of 'AuthType' and one of thefollowing strings:

• 'Server'

5-30

Page 215: Database Toolbox™ II

database

• 'Windows'

Specify 'Windows' for Windows Authentication.

Example: 'AuthType','Windows'

’DriverType’ - Driver type'thin' | 'oci'

Driver type (required only for Oracle), specified as the comma-separatedpair consisting of 'DriverType' and one of the following strings:

• 'thin'

• 'oci'

Example: 'DriverType','thin'

’URL’ - Connection URLstring

Connection URL, specified as the comma-separated pair consisting of'URL' and a string value. If you specify URL, you might not need tospecify any other properties.

OutputArguments

conn - Database connectionDatabase connection object

Database connection, returned as a database connection object. Thedatabase connection object has the following properties:

• Instance

• UserName

• Driver

• URL

• Constructor

• Message

• Handle

5-31

Page 216: Database Toolbox™ II

database

• TimeOut

• AutoCommit

• Type

The native ODBC database connection object,database.ODBCConnection, excludes Driver, URL, andConstructor properties. For database.ODBCConnection, theType property is equal to database.ODBCConnection object.The Handle property for a database.ODBCConnection object isdatabase.internal.ODBCConnectHandle, and for JDBC/ODBC bridgeconnection, it is sun.jdbc.odbc.JdbcOdbcConnection. For ODBC, theInstance property contains the data source name, and, for JDBC, theInstance property contains the database name.

Tips • Use logintimeout before database to set the maximum time for aconnection attempt.

• Alternatively use Visual Query Builder to connect to databases.

• When making a JDBC connection using name-value connectionproperties:

- You can skip the Server parameter when connecting to a databaselocally.

- You can skip the PortNumber parameter when connecting to adatabase server listening on the default port (except for Oracleconnections).

Examples Connect Using the Native ODBC Interface

Connect to the dbtoolboxdemo database using the native ODBCinterface.

Connect to the database with the ODBC data source name,dbtoolboxdemo, using the user name, admin, and password, admin.

conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')

5-32

Page 217: Database Toolbox™ II

database

conn =

ODBCConnection with properties:

Instance: 'dbtoolboxdemo'UserName: 'admin'Message: []Handle: [1x1 database.internal.ODBCConnectHandle]

TimeOut: 0AutoCommit: 0

Type: 'ODBCConnection Object'

database.ODBCConnection returns conn as database.ODBCConnectionobject.

Close the database connection, conn.

close(conn);

ODBC Connection

Connect to the dbtoolboxdemo database.

Connect to the database with the ODBC data source name,dbtoolboxdemo, using the user name, admin, and password, admin.

conn = database('dbtoolboxdemo','admin','admin')

conn =

Instance: 'dbtoolboxdemo'UserName: 'admin'

Driver: []URL: []

Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]Message: []Handle: [1x1 sun.jdbc.odbc.JdbcOdbcConnection]

TimeOut: 0AutoCommit: 'on'

5-33

Page 218: Database Toolbox™ II

database

Type: 'Database Object'

database returns conn as a Database Object.

Close the database connection, conn.

close(conn);

Oracle JDBC Connection Using URL

Connect to an Oracle database using the JDBC driver.

Connect to the database, test_db, using the user name,scott, and password, tiger. Use the JDBC driver,oracle.jdbc.driver.OracleDriver, to make the connection. The URLdefined by the driver vendor is jdbc:oracle:oci7:.

conn = database('test_db','scott','tiger',...'oracle.jdbc.driver.OracleDriver','jdbc:oracle:oci7:')

Oracle JDBC Connection Using Name-Value ConnectionProperties

Connect to an Oracle database using the JDBC driver. Specify thevendor and connection options using name-value pair arguments.

Connect to the database, test_db, using the user name, scott, andpassword, tiger. The Database Server machine name is remotehostand the port number that the server is listening on is 1234.

conn = database('test_db','scott','tiger','Vendor','Oracle',...'DriverType','oci','Server','remotehost','PortNumber',1234)

MySQL JDBC Connection on the Default Port

Connect to a MySQL database via a JDBC driver. Specify the vendorand connection options using name-value pair arguments.

Connect to the database, test_db, on the machine, remotehost. Usethe user name, root, and password, matlab.

conn = database('test_db','root','matlab','Vendor','MySQL',...

5-34

Page 219: Database Toolbox™ II

database

'Server','remotehost')

Microsoft Access Connection to a Database with .accdbFormat

Connect to a Microsoft Access database with .accdb format using anOBDC driver.

Connect to the database, MyDatabase.accdb, using dpath and url.

dbpath = ['C:\Data\Matlab\MyDatabase.accdb'];

url = [['jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ='] dbpath];

con = database('','','','sun.jdbc.odbc.JdbcOdbcDriver', url);

PostGreSQL JDBC Connection to localhost on the Default Port

Connect to a local PostGreSQL database using the JDBC driver. Specifythe vendor and connection options using name-value pair arguments.

Connect to the database, test_db, using the user name, postgres, andpassword, matlab.

conn = database('test_db','postgres','matlab','Vendor','PostGreSQL')

Microsoft SQL Server Windows Authenticated DatabaseConnection

Connect to a Microsoft SQL Server database with integrated WindowsAuthentication using a JDBC driver.

Close MATLAB if it is running.

Insert the path to the database driver JAR file in thejavaclasspath.txt file. The updated path entry should include thefull path to the driver. For example:

C:\DB_Drivers\sqljdbc_2.0\enu\sqljdbc4.jar

Insert the path to the folder containing sqljdbc_auth.dll in thelibrarypath.txt file. The librarypath.txt file is located at:

5-35

Page 220: Database Toolbox™ II

database

$MATLABROOT\toolbox\local\librarypath.txt

The path entry should not include the file name sqljdbc_auth.dll:

C:\DB_Drivers\sqljdbc_2.0\enu\auth\x64

The sqljdbc_auth.dll file is installed in the following location:

<installation>\sqljdbc_<version>\<language>\auth\<arch>

where <installation> is the installation folder of the SQL serverdriver.

• If you are running a 32-bit Java Virtual Machine (JVM), then use thesqljdbc_auth.dll file in the x86 folder, even if the operating systemis the x64 version.

• If you are running a 64-bit JVM on a x64 processor, then use thesqljdbc_auth.dll file in the x64 folder.

• If you are running a 64-bit JVM on a IA-64 processor, then use thesqljdbc_auth.dll file in the IA64 folder.

Start MATLAB.

Use the AuthType parameter to establish a Windows Authenticationconnection.

conn = database('dbName','','', ...'Vendor','Microsoft SQL Server','Server','servername',...'AuthType','Windows')

Definitions JDBC Driver Name and Database Connection URL

The JDBC driver name and database connection URL take differentforms for different databases, as shown in the following table.

5-36

Page 221: Database Toolbox™ II

database

Database JDBC Driver Name and Database URL Example Syntax

IBM Informix JDBC Driver: com.informix.jdbc.IfxDriver

Database URL: jdbc:informix-sqli://161.144.202.206:3000:INFORMIXSERVER=stars

Microsoft SQLServer 2005

JDBC Driver: com.microsoft.sqlserver.jdbc.SQLServerDriver

Database URL:jdbc:sqlserver://localhost:port;database=databasename

MySQL JDBC Driver: twz1.jdbc.mysql.jdbcMysqlDriver

Database URL: jdbc:z1MySQL://natasha:3306/metrics

JDBC Driver: com.mysql.jdbc.Driver

Database URL: jdbc:mysql://devmetrics.mrkps.com/testing

To insert or select characters with encodings that are not default,append the string useUnicode=true&characterEncoding=... to theURL, where ... is any valid MySQL character encoding. For example,useUnicode=true&characterEncoding=utf8.

Oracleoci7 drivers

JDBC Driver: oracle.jdbc.driver.OracleDriver

Database URL: jdbc:oracle:oci7:@rex

Oracleoci8 Drivers

JDBC Driver: oracle.jdbc.driver.OracleDriver

Database URL: jdbc:oracle:oci8:@111.222.333.44:1521:

Database URL: jdbc:oracle:oci8:@frug

Oracle 10Connectionswith JDBC(Thin Drivers)

JDBC Driver: oracle.jdbc.driver.OracleDriverDatabase URL: jdbc:oracle:thin:

OracleThin Drivers

JDBC Driver: oracle.jdbc.driver.OracleDriver

Database URL: jdbc:oracle:thin:@144.212.123.24:1822:

5-37

Page 222: Database Toolbox™ II

database

Database JDBC Driver Name and Database URL Example Syntax

PostgreSQL JDBC Driver: org.postgresql.Driver

Database URL:jdbc:postgresql://host:port/database

PostgreSQLwith SSLConnection

JDBC Driver: org.postgresql.Driver

Database URL: jdbc:postgresql:servername:dbname:ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory&

The trailing & is required.

Sybase SQLServer andSybase SQLAnywhere

JDBC Driver: com.sybase.jdbc.SybDriver

Database URL: jdbc:sybase:Tds:yourhostname:yourportnumber/

See Also close | dexplore | dmd | exec | fastinsert | get |getdatasources | isconnection | isreadonly | logintimeout |ping | querybuilder | supports | update

Concepts • “Database Connection Error Messages” on page 2-8• “Bringing Java Classes into MATLAB Workspace”• “Using the Native ODBC Database Connection” on page 2-12

5-38

Page 223: Database Toolbox™ II

database.catalogs

Purpose Get database catalog names

Syntax P = catalogs(conn)

Description P = catalogs(conn) returns the catalogs for the database connectionconn.

See Also get | database.columns | database.schemas | database.tables

5-39

Page 224: Database Toolbox™ II

database.columns

Purpose Get database table column names

Syntax P = columns(conn)P = columns(conn,C)P = columns(conn,C,S)P = columns(conn,C,S,T)

Description P = columns(conn) returns all columns for all tables given thedatabase connection conn.

P = columns(conn,C) returns all columns for all tables of all schemasfor the given catalog C.

P = columns(conn,C,S) returns the columns for all tables for thegiven catalog C and schema S.

P = columns(conn,C,S,T) returns the columns for the given databaseconnection conn, the catalog C, the schema S, and the table T.

See Also get | database.schemas | database.tables

5-40

Page 225: Database Toolbox™ II

database.fetch

Purpose 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 statementsqlquery, imports data for the open connection object conn, and returnsthe data to results. (For more information on SQL statements, seeexec.)

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

InputArguments

conn

A database connection object.

sqlquery

An SQL statement.

fetchbatchsize

Specifies the number of rows of data to import at a time. Usefetchbatchsize when importing large amounts of data. Retrievingdata in increments, as specified by fetchbatchsize, helps reduceoverall retrieval time. If fetchbatchsize is not provided, a defaultvalue of FetchBatchSize is used. FetchBatchSize is set usingsetdbprefs.

OutputArguments

results

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

Tips • You call the database.fetch function with fetch rather thandatabase.fetch. You implicitly call database.fetch by passing adatabase object, conn, to fetch. The fetch function also works witha cursor object. See cursor.fetch.

5-41

Page 226: Database Toolbox™ II

database.fetch

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

Examples Import Data

Import the productDescription column from the productTable tablein 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 fetchbatchsizeargument.

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

size(results)

ans =

10 1

5-42

Page 227: Database Toolbox™ II

database.fetch

Import Two Columns of Data and View Information Aboutthe Data

Import the InvoiceNumber and Paid columns from the Invoice tablein 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

See Also cursor.fetch | database | exec | fetch | logical

How To • “Retrieving Image Data Types” on page 4-25

5-43

Page 228: Database Toolbox™ II

database.fetch

• “Preference Settings for Large Data Import” on page 3-10

5-44

Page 229: Database Toolbox™ II

database.schemas

Purpose Get database schema names

Syntax P = schemas(conn)

Description P = schemas(conn) returns the schema names for the databaseconnection conn.

See Also get | database.catalogs | database.columns | database.tables

5-45

Page 230: Database Toolbox™ II

database.tables

Purpose Get database table names

Syntax T = tables(conn)T = tables(conn,C)T = tables(conn,C,S)

Description T = tables(conn) returns all tables and table types for the databaseconnection object conn.

T = tables(conn,C) returns all tables and table types for all schemasof the given catalog name C.

T = tables(conn,C,S) returns the list of tables and table types for thedatabase with the catalog name C and schema name S.

See Also get | database.catalogs | database.schemas

5-46

Page 231: Database Toolbox™ II

datainsert

Purpose Export MATLAB data into database table

Syntax datainsert(connect,tablename,fieldnames,data)

Description datainsert(connect,tablename,fieldnames,data) inserts data fromthe MATLAB workspace into a database table.

Tips You can also use the fastinsert function to export MATLAB data intoa database table. The fastinsert function allows more flexibility interms of the date and time string format of input data, but it is slowerthan datainsert.

InputArguments

connect

Database connection object.

tablename

Database table.

fieldnames

String array of database column names.

data

MATLAB cell array or numeric matrix.

If data is a cell array containing MATLAB dates, times, or timestamps,the dates must be date strings of the form yyyy-mm-dd, times must betime strings of the form HH:MM:SS, and timestamps must be stringsof the form yyyy-mm-dd HH:MM:SS.FFF. null entries must be emptystrings and any NaNs in the cell array must be converted to emptystrings before calling datainsert.

MATLAB date numbers and NaNs are supported for insert when data isa numeric array. Date numbers inserted into database date and timecolumns convert to java.sql.Date.

5-47

Page 232: Database Toolbox™ II

datainsert

Examples Export MATLAB cell array data into the field names col1, col2, andcol2 in the 'inserttable' database table:

datainsert(connect,'inserttable',{'col1','col2','col2'},...{33.5 8.77 '2010-07-04'})

Export data from a numeric matrix into a database table:

datainsert(connect,'inserttable',{'col1','col2','col2'},...[33.5 8.77 734323])

See Also fastinsert | insert | update

5-48

Page 233: Database Toolbox™ II

dexplore

Purpose Start SQL Database Explorer to import data

Syntax dexplore

Description dexplore starts Database Explorer, which is the Database Toolboxapp for connecting to a database and importing data to the MATLABworkspace.

Database Explorer is an interactive app that allows you to:

• Create and configure JDBC and ODBC data sources

• Establish multiple connections to databases

• Select tables and columns of interest

• Fine-tune selection using SQL query criteria

• Preview selected data

• Import selected data into MATLAB workspace

• Save generated SQL queries

• Generate MATLAB code

Examples For more information on Database Explorer, after starting DatabaseExplorer, click Help on the Database Explorer Toolstrip:

RelatedExamples

• “Using Database Explorer” on page 3-61

5-49

Page 234: Database Toolbox™ II

dmd

Purpose Construct database metadata object

Syntax dbmeta = dmd(conn)

Description dbmeta = dmd(conn) constructs a database metadata object for thedatabase connection conn. Use get and supports to obtain propertiesof dbmeta. Use dmd and get(dbmeta) to obtain information you needabout a database, such as table names required to retrieve data.

For a list of functions that operate on database metadata objects, enter:

help dmd/Contents

Examples Create a database metadata object dbmeta for the database connectionconn and list its properties:

dbmeta = dmd(conn);v = get(dbmeta)

See Also columns | database | get | supports | tables

5-50

Page 235: Database Toolbox™ II

driver

Purpose Construct database driver object

Syntax d = driver('s')

Description d = driver('s') constructs a database driver object d from s, wheres is a database URL string of the form jdbc:odbc:name or name. Thedriver object d is the first driver that recognizes s.

Examples d = driver('jdbc:odbc:thin:@144.212.123.24:1822:') createsdriver object d.

See Also get | isdriver | isjdbc | isurl | register

5-51

Page 236: Database Toolbox™ II

drivermanager

Purpose Construct database drivermanager object

Syntax dm = drivermanager

Description dm = drivermanager constructs a database drivermanager objectwhich comprises the properties for all loaded database drivers. Use getand set to obtain and change the properties of dm.

Examples Create a database drivermanager object and return its properties.

dm = drivermanagerget(dm)

See Also get | register | set

5-52

Page 237: Database Toolbox™ II

exec

Purpose Execute SQL statement and open cursor

Syntax curs = exec(conn,sqlquery)curs = exec(conn,sqlquery,qTimeOut)

Description curs = exec(conn,sqlquery) executes the SQL statement sqlqueryfor the database connection conn and returns the cursor object curs.

curs = exec(conn,sqlquery,qTimeOut) executes the SQL statementwith a timeout value qTimeOut.

InputArguments

conn - Database connectionconnection object

Database connection, specified as a database connection object createdusing database.

sqlquery - SQL statementSQL string

SQL statement, specified as an SQL string to execute.

Data Typeschar

qTimeOut - Timeout valuescalar

Timeout value, specified as a scalar denoting the maximum amount oftime in seconds exec tries to execute the SQL statement, sqlquery.

Data Typesdouble

OutputArguments

curs - Database cursordatabase cursor object

Database cursor, returned as a database cursor object. The propertiesof this object are different based on the database connection object.

5-53

Page 238: Database Toolbox™ II

exec

For an ODBC/JDBC bridge or a JDBC driver database connection, thecursor object has the following properties.

Property Description

Attributes Not used.

Data Contains the resulting data after executingfetch.

DatabaseObject Database connection object ordatabase.ODBCConnection object thatopened the cursor object.

RowLimit Number of rows to fetch at a time.

SQLQuery SQL statement to execute.

Message Contains the error messages generated fromexecuting the SQL statement. If this propertyis empty, then the SQL statement executedsuccessfully.

Type Database cursor object or database.ODBCCursorobject type.

ResultSet Java result set object.

Cursor Internal Java representation of a cursor object.

Statement Java statement object.

Fetch Internal Java representation of the fetched data.

For a native ODBC connection, the cursor object has only theseproperties from the previous list: Data, RowLimit, SQLQuery, Message,Type, and Statement.

Examples Select Data from a Database Table Using the Native ODBCInterface

Create a connection conn using the native ODBC interface and thedbtoolboxdemo data source.

5-54

Page 239: Database Toolbox™ II

exec

conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')

conn =

ODBCConnection with properties:

Instance: 'dbtoolboxdemo'UserName: 'admin'Message: []Handle: [1x1 database.internal.ODBCConnectHandle]

TimeOut: 0AutoCommit: 0

Type: 'ODBCConnection Object'

conn has an empty Message property, which means a successfulconnection.

Select data from productTable that you access using thedatabase.ODBCConnection object, conn. Assign the returned cursorobject to the variable curs.

sqlquery = 'select * from productTable';curs = exec(conn,sqlquery)

curs =

ODBCCursor with properties:

Data: 0RowLimit: 0SQLQuery: 'select * from productTable'Message: []

Type: 'ODBCCursor Object'Statement: [1x1 database.internal.ODBCStatementHandle]

With the native ODBC interface, exec returns curs asdatabase.ODBCCursor object instead of a Database Cursor Object.

5-55

Page 240: Database Toolbox™ II

exec

After you finish with the cursor object, close the cursor.

close(curs);

Select Data from a Database Table

Using the dbtoolboxdemo data source, select data from the supplierstable that you access using the database connection, conn. Assign thereturned cursor object to the variable curs.

sqlquery = 'select City from suppliers';curs = exec(conn,sqlquery)

curs =

Attributes: []Data: 0

DatabaseObject: [1x1 database]RowLimit: 0SQLQuery: 'select City from suppliers'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: 0

After you finish with the cursor object, close the cursor.

close(curs);

Select Data from a Database Table with a Timeout Value

Using the dbtoolboxdemo data source, select data from productTablethat you access using the database connection conn with a timeout of10 seconds. The timeout value specifies the maximum amount of time

5-56

Page 241: Database Toolbox™ II

exec

exec tries to execute the SQL statement. Assign the returned cursorobject to the variable curs.

sqlquery = 'select * from productTable';curs = exec(conn,sqlquery,10)

curs =

Attributes: []Data: 0

DatabaseObject: [1x1 database]RowLimit: 0SQLQuery: 'select * from productTable'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: 0

After you finish with the cursor object, close the cursor.

close(curs);

Select One Column of Data from the Database Table

Using dbtoolboxdemo data source, select stockNumber data from theproductTable table that you access using the database connectionconn. Assign the SQL statement to the variable sqlquery and assignthe returned cursor to the variable curs.

sqlquery = 'select stocknumber from productTable';curs = exec(conn,sqlquery);

After you are finished with the cursor object, close the cursor.

close(curs);

5-57

Page 242: Database Toolbox™ II

exec

Use a Variable in a Query

Using dbtoolboxdemo data source, select data from the productTabletable that you access using the database connection conn, whereproductdesc is a variable. In this example, you are prompted tospecify the product description. Your input is assigned to the variableproductdesc.

productdesc = input('Enter your product description: ', 's')

The following prompt appears.

Enter your product description:

Type the following into the MATLAB Command Window.

Train Set

To perform the query using your input, run the following code.

sqlquery = ['select * from productTable' ...'where productDescription = ' '''' productdesc ''''];curs = exec(conn,sqlquery);curs = fetch(curs);curs.Data

ans =

[8] [212569] [1001] [5] 'Train Set'

The select statement is created by using square brackets toconcatenate the two strings select * from productTable whereproductDescription = and 'productdesc'. The pairs of fourquotation marks are needed to create the pair of single quotation marksthat appears in the SQL statement around productdesc. The outer twomarks delineate the next string to concatenate, and two marks arerequired inside them to denote a quotation mark inside a string.

5-58

Page 243: Database Toolbox™ II

exec

Perform the query without a variable.

sqlquery = ['select * from productTable' ...'where productDescription = ' '''Engine Kit'''];curs = exec(conn,sqlquery);curs = fetch(curs);curs.Data

ans =

[7] [389123] [1007] [16] 'Engine Kit'

After you are finished with the cursor object, close the cursor.

close(curs);

Roll Back or Commit Data Exported to the Database Table

Use exec to roll back or commit data after running a fastinsert,insert, or update for which the AutoCommit flag is off.

Roll back data for the database connection conn.

sqlquery = 'rollback';exec(conn,sqlquery);

When you don’t specify an output argument, MATLAB returns theresults of calling exec into cursor object ans. Assign ans to variablecurs so that MATLAB does not overwrite the cursor object. After youare finished with the cursor object, close the cursor.

curs = ans;close(curs);

Commit the data.

sqlquery = 'commit';exec(conn,sqlquery);

5-59

Page 244: Database Toolbox™ II

exec

After you are finished with the cursor object, close the cursor.

curs = ans;close(curs);

Change the Database Connection Catalog

Change the catalog for the database connection conn to intlprice.

sqlquery = 'Use intlprice';curs = exec(conn,sqlquery);

After you are finished with the cursor object, close the cursor.

close(curs);

Create a Table and Add a New Column

Use the SQL CREATE command to create the table.

sqlquery = ['CREATE TABLE Person(LastName varchar, '...'FirstName varchar,Address varchar,Age int)'];

Create the table for the database connection object conn.

exec(conn,sqlquery);

Use the SQL ALTER command to add a new column, City, to the table.

sqlquery = 'ALTER TABLE Person ADD City varchar(30)';curs = exec(conn,sqlquery);

After you are finished with the cursor object, close the cursor.

close(curs);

5-60

Page 245: Database Toolbox™ II

exec

Run a Stored Procedure and Return the Result Set

Use the JDBC interface to connect to a Microsoft SQL Server database,run a stored procedure, and return the result set. For this example, thestored procedure getSupplierInfo is defined in the Microsoft SQLServer database. This stored procedure returns the supplier informationfor suppliers of a given city. The procedure definition is as follows.

CREATE PROCEDURE dbo.getSupplierInfo(@cityName varchar(20))

ASBEGIN-- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.SET NOCOUNT ON;

SELECT * from suppliers where city = @cityNameENDGO

For Microsoft SQL Server, the statement 'SET NOCOUNT ON' suppressesthe results of insert, update or any non-select statements that mightbe before the final select query so you can fetch the results of the selectquery.

Use exec when the stored procedure returns one or more result sets. Forprocedures that return output parameters, use runstoredprocedure.

Using the JDBC interface, connect to the Microsoft SQL Serverdatabase called 'test_db' with the user name 'root' and password'matlab' using port number 1234. This example assumes yourdatabase server is located on the machine servername.

conn = database('test_db','root','matlab',...'Vendor','Microsoft SQL Server',...'Server','servername','PortNumber',1234)

conn =

5-61

Page 246: Database Toolbox™ II

exec

Instance: 'test_db'UserName: 'root'

Driver: []URL: []

Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]Message: []Handle: [1x1 com.microsoft.sqlserver.jdbc.SQLServerConnection]

TimeOut: 0AutoCommit: 'on'

Type: 'Database Object'

database returns conn, a connection Database Object for the'test_db' database.

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

To return the result set in table format, use setdbprefs to set'DataReturnFormat' to 'table'.

setdbprefs('DataReturnFormat','table');

Run the stored procedure, getSupplierInfo, to return supplierinformation for the city of New York using exec with conn.

sqlquery = '{call getSupplierInfo(''New York'')}';curs = exec(conn,sqlquery)

curs =

Attributes: []Data: 0

DatabaseObject: [1x1 database]RowLimit: 0SQLQuery: '{call getSupplierInfo('New York')}'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 com.microsoft.sqlserver.jdbc.SQLServerResultSet]

5-62

Page 247: Database Toolbox™ II

exec

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]Statement: [1x1 com.microsoft.sqlserver.jdbc.SQLServerStateme

Fetch: 0

exec returns a Database Cursor Object, curs, containing the supplierinformation.

Retrieve supplier data from curs using fetch.

curs = fetch(curs)

curs =

Attributes: []Data: [3x5 table]

DatabaseObject: [1x1 database]RowLimit: 0SQLQuery: '{call getSupplierInfo('New York')}'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 com.microsoft.sqlserver.jdbc.SQLServerResultS

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]Statement: [1x1 com.microsoft.sqlserver.jdbc.SQLServerStateme

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

curs contains the supplier data from running the stored procedure,getSupplierInfo, in table format.

Display the supplier data in table format by accessing the contents ofthe Data element of curs.

curs.Data

ans =

SupplierNumber SupplierName City-------------- ------------------ ----------1001 'Wonder Products' 'New York'

5-63

Page 248: Database Toolbox™ II

exec

1006 'ACME Toy Company' 'New York'1012 'Aunt Jemimas' 'New York'

Country FaxNumber--------------- --------------'United States' '212 435 1617''United States' '212 435 1618''USA' '14678923104'

>>

Close the Database Cursor Object, curs, and then close theconnection Database Object, conn.

close(curs);close(conn);

Run a Custom Database Function

This example shows how to run a user-defined database function onMicrosoft SQL Server.

Consider a database function, get_prodCount, that gets entry countsin a table, productTable.

CREATE FUNCTION dbo.get_prodCount()RETURNS intASBEGIN

DECLARE @PROD_COUNT intSELECT @PROD_COUNT = count(*) from productTableRETURN(@PROD_COUNT)

ENDGO

Use the database connection, conn, to execute the custom functionfrom MATLAB.

5-64

Page 249: Database Toolbox™ II

exec

sqlquery = 'SELECT dbo.get_prodCount() as num_products';curs = exec(conn,sqlquery);curs = fetch(curs);

After you are finished with the cursor object, close the cursor.

close(curs);

See Also close | database | fastinsert | fetch | procedures |querybuilder | querytimeout | resultset | rsmd | set |update

Concepts • “Using the exec Function” on page 4-39• “Using the Native ODBC Database Connection” on page 2-12• “Data Retrieval Restrictions” on page 1-7

5-65

Page 250: Database Toolbox™ II

exportedkeys

Purpose Retrieve information about exported foreign keys

Syntax e = exportedkeys(dbmeta, 'cata', 'sch')e = exportedkeys(dbmeta, 'cata', 'sch', 'tab')

Description e = exportedkeys(dbmeta, 'cata', 'sch') returns foreign exportedkey information (that is, information about primary keys that arereferenced by other tables) for the schema sch, of the catalog cata, forthe database whose database metadata object is dbmeta.

e = exportedkeys(dbmeta, 'cata', 'sch', 'tab') returnsexported foreign key information for the table tab, in the schema sch, ofthe catalog cata, for the database whose database metadata object isdbmeta.

Examples Get foreign exported key information for the schema SCOTT for thedatabase metadata object dbmeta.

e = exportedkeys(dbmeta,'orcl','SCOTT')e =

Columns 1 through 7'orcl' 'SCOTT' 'DEPT' 'DEPTNO' 'orcl' ...'SCOTT' 'EMP'

Columns 8 through 13'DEPTNO' '1' 'null' '1' 'FK_DEPTNO'...

'PK_DEPT'

The results show the foreign exported key information.

Column Description Value

1 Catalog containing primary key that isexported

null

2 Schema containing primary key that isexported

SCOTT

5-66

Page 251: Database Toolbox™ II

exportedkeys

Column Description Value

3 Table containing primary key that isexported

DEPT

4 Column name of primary key that isexported

DEPTNO

5 Catalog that has foreign key null

6 Schema that has foreign key SCOTT

7 Table that has foreign key EMP

8 Foreign key column name, that is thecolumn name that references the primarykey in another table

DEPTNO

9 Sequence number within the foreign key 1

10 Update rule, that is, what happens to theforeign key when the primary key updates

null

11 Delete rule, that is, what happens to theforeign key when the primary key is deleted

1

12 Foreign key name FK_DEPTNO

13 Primary key name that is referenced byforeign key

PK_DEPT

In the schema SCOTT, only one primary key is exported to (referenced by)another table. DEPTNO, the primary key of the table DEPT, is referencedby the field DEPTNO in the table EMP. The referenced table is DEPT andthe referencing table is EMP. In the DEPT table, DEPTNO is an exportedkey. Reciprocally, the DEPTNO field in the table EMP is an imported key.

For a description of codes for update and delete rules, see thegetExportedKeys property on the Oracle Java Web site:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/DatabaseMetaData

See Also crossreference | dmd | get | importedkeys | primarykeys

5-67

Page 252: Database Toolbox™ II

fastinsert

Purpose Add MATLAB data to database table

Alternatives • Export data using Visual Query Builder with Data operation setto Insert.

• Use the datainsert function. The datainsert function is fasterthan the fastinsert function, but you must enter dates and timesin a specific format.

Syntax fastinsert(conn,'tablename',colnames,exdata)

Description fastinsert(conn,'tablename',colnames,exdata) exports recordsfrom the MATLAB variable exdata into new rows in an existingdatabase table tablename via the connection conn. The variable exdatacan be a cell array, numeric matrix, table, dataset, or structure. You donot specify the type of data you are exporting; the data is exported inits current MATLAB format. Specify column names for tablename asstrings in the MATLAB cell array colnames. If exdata is a structure,field names in the structure must match colnames. If exdata is a tableor a dataset, the variable names in the table or dataset must exactlymatch colnames.

The status of the AutoCommit flag determines whether fastinsertautomatically commits the data to the database. Use get to view theAutoCommit flag status for the connection and use set to change it. Usecommit or issue an SQL commit statement using exec to commit thedata to the database. Use rollback or issue an SQL rollback statementusing exec to roll back the data.

Use update to replace existing data in a database.

When working with a JDBC driver connection or a JDBC-ODBC bridgeconnection established using the database function, fastinsert offersimproved performance over insert. This is because insert createsand executes an SQL insert query for each row of data. fastinsertcreates the insert query only once and then allows for the data valuesto be plugged in. All rows of data get inserted as a batch resulting inan overall faster performance over insert. However, since fastinsert

5-68

Page 253: Database Toolbox™ II

fastinsert

relies more on driver functions compared to insert, it is possible insome edge case scenarios that the driver functions do not work asexpected. In such cases, insert might be preferred, especially if thedata to be inserted is small. datainsert is faster than fastinsert butneeds data to be formatted in a specific way and accepts cell arrays andnumeric matrices as input data.

When working with a native ODBC connection established using thedatabase.ODBCConnection function, fastinsert and insert areidentical. datainsert is not supported for native ODBC connections.

Note fastinsert supports the native ODBC interface. To insertdates and timestamps with the native ODBC interface, use the format'YYYY-MM-DD HH:MM:SS.MS'.

Tips • The fastinsert function replaces the insert function. The twofunctions have the same syntax, but fastinsert provides betterperformance and supports more object types than insert. Iffastinsert does not work as expected, try running insert.

• To reduce conversion time, convert dates to serial date numbersusing datenum before calling fastinsert.

• To insert dates and timestamps with the native ODBC interface, usethe format 'YYYY-MM-DD HH:MM:SS.MS'.

• To insert data into a structure, table, or dataset, use the followingspecial formatting. Each field or variable in a structure, table ordataset must be a cell array or double vector of size m*1, where m isthe number of rows to be inserted.

• The order of records in your database is not constant. Use values incolumn names to identify records.

• If an error message like the following appears when you runfastinsert, the table might be open in edit mode.

[Vendor][ODBC Product Driver] The database engine could

5-69

Page 254: Database Toolbox™ II

fastinsert

not lock table 'TableName' because it is already in useby another person or process.

In this case, close the table in the database and rerun the fastinsertfunction.

Examples Example 1 — Insert a Table Record Using Native ODBC

1 Create a connection conn using the native ODBC interface and thedbtoolboxdemo data source.

conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')

conn =

ODBCConnection with properties:

Instance: 'dbtoolboxdemo'UserName: 'admin'Message: []Handle: [1x1 database.internal.ODBCConnectHandle]

TimeOut: 0AutoCommit: 0

Type: 'ODBCConnection Object'

conn has an empty Message property, which means a successfulconnection.

2 Select and display the data from the productTable.

curs = exec(conn, 'select * from productTable');curs = fetch(curs);curs.Data

ans =

productNumber stockNumber supplierNumber unitCost produ------------- ----------- -------------- -------- -----

5-70

Page 255: Database Toolbox™ II

fastinsert

9 125970 1003 13 'V8 212569 1001 5 'T7 389123 1007 16 'E2 400314 1002 9 'P4 400339 1008 21 'S1 400345 1001 14 'B5 400455 1005 3 'T6 400876 1004 8 'S3 400999 1009 17 'S

10 888652 1006 24 'T

3 Store the column names of productTable in a cell array.

colnames = {'productNumber' 'stockNumber' 'supplierNumber' ...'unitCost' 'productDescription'};

4 Store the data for the insert in a cell array, exdata. The datacontains productNumber equal to 11, stockNumber equal to 500565,supplierNumber equal to 1010, unitCost equal to $20, andproductDescription equal to 'Cooking Set'. Then, convert the cellarray to a table, exdata_table.

exdata = {11, 500565, 1010, 20, 'Cooking Set'};exdata_table = cell2table(exdata,'VariableNames',colnames)

exdata_table =

productNumber stockNumber supplierNumber unitCost pr------------- ----------- -------------- -------- -11 500565 1010 20 'C

5 Insert the table data into the productTable.

fastinsert(conn, 'productTable', colnames, exdata_table);

6 Display the data from the productTable again.

curs = exec(conn, 'select * from productTable');

5-71

Page 256: Database Toolbox™ II

fastinsert

curs = fetch(curs);curs.Data

ans =

productNumber stockNumber supplierNumber unitCost produ------------- ----------- -------------- -------- -----9 125970 1003 13 'Vict8 212569 1001 5 'Trai7 389123 1007 16 'Engi2 400314 1002 9 'Pain4 400339 1008 21 'Spac1 400345 1001 14 'Buil5 400455 1005 3 'Tin6 400876 1004 8 'Sail3 400999 1009 17 'Slin

10 888652 1006 24 'Tedd11 500565 1010 20 'Cook

A new row appears in the productTable with the data fromexdata_table.

Example 2 — Insert a Record

1 Using the dbtoolboxdemo data source, insert a record consistingof three columns, productNumber, Quantity, and Price into theinventoryTable. productNumber is 7777, Quantity is 100, andPrice is 50.00. The database connection is conn. Assign the datato the cell array exdata.

exdata = {7777, 100, 50.00}

2 Create a cell array containing the column names in inventoryTable.

colnames = {'productNumber', 'Quantity', ' Price'}

3 Insert the data into the database.

5-72

Page 257: Database Toolbox™ II

fastinsert

fastinsert(conn, 'inventoryTable', colnames, exdata)

The row of data is added to the inventoryTable table.

Example 3 — Insert Multiple Records

• Using the dbtoolboxdemo data source, insert multiple rows of dataconsisting of three columns, productNumber, Quantity, and Priceinto the inventoryTable.

exdata = {7778, 125, 23.00; 7779, 1160, 14.7; 7780, 150, 54.5}

• Create a cell array containing the column names in inventoryTable.

colnames = {'productNumber', 'Quantity', ' Price'}

• Insert the data into the database.

fastinsert(conn, 'inventoryTable', colnames, exdata)

The records are inserted into the table.In addition, there are three sample files for different database vendorsthat demonstrate bulk insert:

• matlabroot/toolbox/database/dbdemos/mssqlserverbulkinsert.m

• matlabroot/toolbox/database/dbdemos/mysqlbulkinsert.m

• matlabroot/toolbox/database/dbdemos/oraclebulkinsert.m

Example 4 — Import Records, Perform Calculations, andExport Data

This example shows how to retrieve sales data from a salesVolumetable, calculate the sum of sales for 1 month, store this data in a cellarray, and export this data to a yearlySales table.

1 Connect to the data source, dbtoolboxdemo, if needed.

conn = database('dbtoolboxdemo', '', '');

5-73

Page 258: Database Toolbox™ II

fastinsert

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

2 Use setdbprefs to set the format for retrieved data to numeric.

setdbprefs('DataReturnFormat','numeric')

3 Import 10 rows of data the March column of data from thesalesVolume table.

curs = exec(conn, 'select March from salesVolume');curs = fetch(curs);

4 Assign the data to the MATLAB workspace variable AA.

AA = curs.DataAA =

981141489018002600280080015001000821

5 Calculate the sum of the March sales and assign the result to thevariable sumA.

sumA = sum(AA(:))sumA =

14606

6 Assign the month and sum of sales to a cell array to export to adatabase. Put the month in the first cell of exdata.

5-74

Page 259: Database Toolbox™ II

fastinsert

exdata(1,1) = {'March'}exdata =

'March'

Put the sum in the second cell of exdata.

exdata(1,2) = {sumA}exdata =

'March' [14606]

7 Define the names of the columns to which to export data. In thisexample, the column names are Month and salesTotal, from theyearlySales table in the dbtoolboxdemo database. Assign the cellarray containing the column names to the variable colnames.

colnames = {'Month','salesTotal'};

8 Use the get function to determine the current status of theAutoCommit database flag. This status determines whether theexported data is automatically committed to the database. If theflag is off, you can undo an update; if it is on, data is automaticallycommitted to the database.

get(conn, 'AutoCommit')ans =on

The AutoCommit flag is set to on, so the exported data is automaticallycommitted to the database.

9 Use the fastinsert function to export the data into the yearlySalestable. Pass the following arguments to this function.

• conn, the connection object for the database

• yearlySales, the name of the table to which you are exportingdata

• The cell arrays colnames and exdata

5-75

Page 260: Database Toolbox™ II

fastinsert

fastinsert(conn, 'yearlySales', colnames, exdata)

fastinsert appends the data as a new record at the end of theyearlySales table.

10 In Microsoft Access, view the yearlySales table to verify the results.

11 Close the cursor.

close(curs);

Example 5 — Insert Numeric Data

Using the dbtoolboxdemo data source, export exdata, a numeric matrixconsisting of three columns, into the inventoryTable table.

exdata = [25, 439, 60.00]

fastinsert(conn, 'inventoryTable', {'productNumber','Quantity', 'Price'}, exdata)

Example 6 — Insert and Commit Data

1 Working with the dbtoolboxdemo data source, use the SQL commitfunction to commit data to a database after it has been inserted. TheAutoCommit flag is off.

Insert the cell array exdata into the column names colnames of theinventoryTable table.

set(conn, 'AutoCommit', 'off')exdata = {157, 358, 740.00}colnames = {'productNumber', 'Quantity', ' Price'}fastinsert(conn, 'inventoryTable', colnames, exdata)commit(conn)

5-76

Page 261: Database Toolbox™ II

fastinsert

Alternatively, commit the data using an SQL commit statement withthe exec function.

cursor = exec(conn,'commit');

Example 7 — Insert BOOLEAN Data

1 Using the dbtoolboxdemo data source, insert BOOLEAN data (which isrepresented as MATLAB type logical) into a database.

conn = database('dbtoolboxdemo', '', '');P.InvoiceNumber{1} = 2101;P.Paid{1}=logical(1);fastinsert(conn,'Invoice',...{'InvoiceNumber';'Paid'}, P)

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

2 View the new record in the database to verify that the Paid field isBOOLEAN. In some databases, the MATLAB logical value 0 is shownas a BOOLEAN false, No, or a cleared check box.

See Also commit | database | exec | insert | logical | querybuilder |rollback | set | update

Tutorials • “Getting Started with Visual Query Builder” on page 3-2

How To • “Using the Native ODBC Database Connection” on page 2-12

5-77

Page 262: Database Toolbox™ II

fetch

Purpose Import data into MATLAB workspace from cursor object or fromexecution of SQL statement

Syntax curs = fetch(curs)curs = fetch(curs,rowlimit)

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

Description curs = fetch(curs) imports all rows of data into the cursor objectcurs from the open SQL cursor object curs.

curs = fetch(curs,rowlimit) imports rows of data up to themaximum number of rows rowlimit.

results = fetch(conn,sqlquery) executes the SQL statementsqlquery, imports all rows of data in batches for the open databaseconnection conn, and returns the resulting data results.

results = fetch(conn,sqlquery,fetchbatchsize) imports all rowsof data in batches of a specified number of rows fetchbatchsize ata time.

InputArguments

curs - Database cursordatabase cursor object

Database cursor, specified as an open SQL database cursor objectcreated using exec.

conn - Database connectionconnection object

Database connection, specified as a database connection object createdusing database.

sqlquery - SQL statement

5-78

Page 263: Database Toolbox™ II

fetch

SQL string

SQL statement, specified as an SQL string to execute.

Data Typeschar

rowlimit - Row limitscalar

Row limit, specified as a scalar denoting the number of rows of data toimport from the open SQL cursor object, curs.

Data Typesdouble

fetchbatchsize - Fetch batch sizescalar

Fetch batch size, specified as a scalar denoting the number of rows ofdata to batch at a time. Use fetchbatchsize when importing largeamounts of data. Retrieving data in batches helps reduce overallretrieval time. If fetchbatchsize is not provided, a default value of'FetchBatchSize' is used. 'FetchBatchSize' is set using setdbprefs.

Data Typesdouble

OutputArguments

curs - Database cursordatabase cursor object

Database cursor, returned as a database cursor object populated withfetched data in the Data property.

results - Result datacell array | table | data set | structure | numeric matrix

Result data, returned as a cell array, table, data set, structure, ornumeric matrix as specified by 'DataReturnFormat' in setdbprefs.

5-79

Page 264: Database Toolbox™ II

fetch

Examples Import All Rows of Data with the Native ODBC InterfaceUsing the Cursor Object

Create a connection conn using the native ODBC interface and thedbtoolboxdemo data source.

conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')

conn =

ODBCConnection with properties:

Instance: 'dbtoolboxdemo'UserName: 'admin'Message: []Handle: [1x1 database.internal.ODBCConnectHandle]

TimeOut: 0AutoCommit: 0

Type: 'ODBCConnection Object'

conn has an empty Message property, which means a successfulconnection.

Working with the dbtoolboxdemo data source, use fetch to import alldata into the database.ODBCCursor object, curs, and store the data ina cell array contained in the cursor object field curs.Data.

curs = exec(conn,'select productDescription from productTable');

curs = fetch(curs)

curs =

ODBCCursor with properties:

Data: {10x1 cell}

RowLimit: 0

SQLQuery: 'select productDescription from productTable'

Message: []

5-80

Page 265: Database Toolbox™ II

fetch

Type: 'ODBCCursor Object'

Statement: [1x1 database.internal.ODBCStatementHandle]

With the native ODBC interface, curs returns an ODBCCursor Objectinstead of a Database Cursor Object.

View the contents of the Data element in the cursor object.

curs.Data

ans =

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

After you are finished with the cursor object, close the cursor object.

close(curs);

Import All Rows of Data Using the Cursor Object

Working with the dbtoolboxdemo data source, use exec to select datain column City, for example, in table suppliers. Then, use fetch toimport all data from the SQL statement into the cursor object curs,and store the data in a cell array contained in the cursor object fieldcurs.Data.

curs = exec(conn,'select City from suppliers');

curs = fetch(curs)

curs =

5-81

Page 266: Database Toolbox™ II

fetch

Attributes: []

Data: {10x1 cell}

DatabaseObject: [1x1 database]

RowLimit: 0

SQLQuery: 'select City from suppliers'

Message: []

Type: 'Database Cursor Object'

ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]

Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

View the contents of the Data element in the cursor object.

curs.Data

ans =

'New York''London''Adelaide''Dublin''Boston''New York''Wellesley''Nashua''London''Belfast'

After you are finished with the cursor object, close the cursor object.

close(curs);

Import a Specified Number of Rows Using the Cursor Object

Working with the dbtoolboxdemo data source, use the rowlimitargument to retrieve only the first three rows of data.

5-82

Page 267: Database Toolbox™ II

fetch

curs = exec(conn, 'select productdescription from producttable');curs = fetch(curs, 3)

curs =

Attributes: []Data: {3x1 cell}

DatabaseObject: [1x1 database]RowLimit: 0SQLQuery: 'select productdescription from producttable'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

View the data.

curs.Data

ans =

'Victorian Doll''Train Set''Engine Kit'

Rerun the fetch function to return the second three rows of data.

curs = fetch(curs, 3);

View the data.

curs.Data

ans =

'Painting Set'

5-83

Page 268: Database Toolbox™ II

fetch

'Space Cruiser''Building Blocks'

After you are finished with the cursor object, close the cursor object.

close(curs);

Import Rows Iteratively Until You Retrieve All Data Usingthe Cursor Object

Working with the dbtoolboxdemo data source, use the rowlimitargument to retrieve the first two rows of data, and then rerun theimport using a while loop, retrieving two rows at a time. Continue untilyou have retrieved all data, which occurs when curs.Data is 'No Data'.

curs = exec(conn, 'select productdescription from producttable');% Initialize rowlimitrowlimit = 2% Check for more data. Retrieve and display all data.while ~strcmp(curs.Data, 'No Data')curs=fetch(curs,rowlimit);curs.Data(:)

end

rowlimit =

2

ans =

'Victorian Doll''Train Set'

ans =

'Engine Kit'

5-84

Page 269: Database Toolbox™ II

fetch

'Painting Set'

ans =

'Space Cruiser''Building Blocks'

ans =

'Tin Soldier''Sail Boat'

ans =

'Slinky''Teddy Bear'

ans ='No Data'

After you are finished with the cursor object, close the cursor object.

close(curs);

Import Numeric Data Using the Cursor Object

Working with the dbtoolboxdemo data source, import a column ofnumeric data, using the setdbprefs function to specify numeric asthe format for the retrieved data.

curs=exec(conn, 'select unitCost from productTable');setdbprefs('DataReturnFormat','numeric')curs=fetch(curs,3);curs.Data

5-85

Page 270: Database Toolbox™ II

fetch

ans =

135

16

After you are finished with the cursor object, close the cursor object.

close(curs);

Import BOOLEAN Data Using the Cursor Object

Import data that includes a BOOLEAN field, using the setdbprefsfunction to specify cellarray as the format for the retrieved data.

curs=exec(conn, ['select InvoiceNumber, '...'Paid from Invoice']);setdbprefs('DataReturnFormat','cellarray')curs=fetch(curs,5);A=curs.Data

A =

[ 2101] [0][ 3546] [1][33116] [1][34155] [0][34267] [1]

View the class of the second column of A.

class(A{1,2})

ans =logical

After you are finished with the cursor object, close the cursor object.

close(curs);

5-86

Page 271: Database Toolbox™ II

fetch

Perform Incremental Fetch Using the Cursor Object

Working with the dbtoolboxdemo data source, retrieve dataincrementally to avoid Java heap errors. Use fetch with thesetdbprefs properties for FetchInBatches and FetchBatchSize tofetch large data sets.

setdbprefs('FetchInBatches', 'yes');setdbprefs('FetchBatchSize', '2');conn = database('dbtoolboxdemo', '', '');curs = exec(conn, 'select * from productTable');curs = fetch(curs);A = curs.Data

A =

[ 9] [125970] [1003] [13] 'Victorian Doll'[ 8] [212569] [1001] [ 5] 'Train Set'[ 7] [389123] [1007] [16] 'Engine Kit'[ 2] [400314] [1002] [ 9] 'Painting Set'[ 4] [400339] [1008] [21] 'Space Cruiser'[ 1] [400345] [1001] [14] 'Building Blocks'[ 5] [400455] [1005] [ 3] 'Tin Soldier'[ 6] [400876] [1004] [ 8] 'Sail Boat'[ 3] [400999] [1009] [17] 'Slinky'[10] [888652] [1006] [24] 'Teddy Bear'

fetch internally retrieves data in increments of two rows at a time.Tune the FetchBatchSize setting depending on the size of the resultsetyou expect to fetch. For example, if you expect about 100,000 rows inthe output, a batch size of 10,000 is a good starting point. The largerthe FetchBatchSize value, the fewer trips between Java and MATLAB,and the memory consumption is greater for each batch. The optimalvalue for FetchBatchSize is decided based on several factors such asthe size per row being retrieved, the Java heap memory value, thedriver’s default fetch size, and system architecture, and hence, mayvary from site to site.

5-87

Page 272: Database Toolbox™ II

fetch

If 'FetchInBatches' is set to 'yes' and the total number of rowsfetched is less than 'FetchBatchSize', MATLAB shows a warningmessage and then fetches all the rows. The message is: Batch sizespecified was larger than the number of rows fetched.

You can exercise a row limit on the final output even when theFetchInBatches setting is 'yes'.

setdbprefs('FetchInBatches', 'yes');setdbprefs('FetchBatchSize', '2');curs = exec(conn, 'select * from productTable');curs = fetch(curs, 3);A = curs.Data

A =

[9] [125970] [1003] [13] 'Victorian Doll'[8] [212569] [1001] [ 5] 'Train Set'[7] [389123] [1007] [16] 'Engine Kit'

In this case, fetch retrieves the first three rows of productTable, tworows at a time.

After you are finished with the cursor object, close the cursor object.

close(curs);

Import Data Using the Database Connection Object

fetch automatically imports data from the specified SQL statementwhen you pass a database object, conn, as the first argument. Use thisexample when using an ODBC/JDBC bridge or a JDBC interface. Forthe native ODBC interface, use curs as the input argument.

Using the dbtoolboxdemo data source that you access using thedatabase connection object, conn, import the productDescriptioncolumn from productTable. Set the data return format to 'cellarray'using setdbprefs.

5-88

Page 273: Database Toolbox™ II

fetch

setdbprefs('DataReturnFormat','cellarray');sqlquery = 'select productdescription from productTable';

results = fetch(conn, sqlquery)

results =

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

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

size(results)

ans =

10 1

Import Data with fetchbatchsize Using the DatabaseConnection Object

fetch automatically imports data from the specified SQL statementwhen you pass a database object, conn, as the first argument. Use thisexample when using an ODBC/JDBC bridge or a JDBC interface. Forthe native ODBC interface, use curs as the input argument.

Using the dbtoolboxdemo data source that you access using thedatabase connection object, conn, import the productDescriptioncolumn from the productTable by using the fetchbatchsize argument.

setdbprefs('DataReturnFormat','cellarray');

5-89

Page 274: Database Toolbox™ II

fetch

sqlquery = 'select productdescription from productTable';fetchbatchsize = 5;

results = fetch(conn,sqlquery,fetchbatchsize);

fetch returns all the data by importing it in batches of five rows ata time.

Import Two Columns of Data and View Information Aboutthe Data Using the Database Connection Object

fetch automatically imports data from the specified SQL statementwhen you pass a database object, conn, as the first argument. Use thisexample when using an ODBC/JDBC bridge or a JDBC interface. Forthe native ODBC interface, use curs as the input argument.

Using the dbtoolboxdemo data source that you access using thedatabase connection object, conn, import the InvoiceNumber andPaid columns from the Invoice table. Set the data return format to'cellarray' using setdbprefs.

setdbprefs('DataReturnFormat','cellarray');sqlquery = 'select InvoiceNumber, Paid from Invoice';

results = fetch(conn, sqlquery);

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 =

5-90

Page 275: Database Toolbox™ II

fetch

[2101] [0]

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

class(results{1,2})

ans =

logical

See Also close | database | setdbprefs | exec | logical

RelatedExamples

• “Retrieving Image Data Types” on page 4-25

Concepts • “Using the fetch Function” on page 4-42• “Using the Native ODBC Database Connection” on page 2-12• “Preference Settings for Large Data Import” on page 3-10• “Data Retrieval Restrictions” on page 1-7

5-91

Page 276: Database Toolbox™ II

fetchmulti

Purpose Import data from multiple resultsets

Syntax curs = fetchmulti(curs)

Description curs = fetchmulti(curs) imports data from the open SQL cursorobject curs into the object curs, where the open SQL cursor objectcontains multiple resultsets.

Multiple resultsets are retrieved via exec with a sqlquery statementthat runs a stored procedure consisting of two select statements.

cursmulti.Data contains data from each resultset associated withcursmulti.Statement. cursmulti.Data is a cell array consisting of cellarrays, structures, or numeric matrices as specified in setdbprefs; thedata type is the same for all resultsets.

Examples Use exec to run a stored procedure that includes multiple selectstatements and fetchmulti to retrieve the resulting multiple resultsets.

conn = database(...)setdbprefs('DataReturnFormat','cellarray')curs = exec(conn, '{call sp_1}');curs = fetchmulti(curs)Attributes: []

Data: {{10x1 cell} {12x4 cell}}DatabaseObject: [1x1 database]

RowLimit: 0SQLQuery: '{call sp_1}'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet][1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: ...[1x1 com.mathworks.toolbox.database.sqlExec]

Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement][1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: ...[1x1 com.mathworks.toolbox.database.fetchTheData]

5-92

Page 277: Database Toolbox™ II

fetchmulti

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

See Also fetch | database | exec | setdbprefs

5-93

Page 278: Database Toolbox™ II

get

Purpose Retrieve object properties

Syntax v = get(object)v = get(object, 'property')v.property

Description v = get(object) returns a structure that contains object and itscorresponding properties, and assigns the structure to v.

v = get(object, 'property') retrieves the value of property forobject and assigns the value to v.

v.property returns the value of property after you have created vby running get.

Use set(object) to view a list of writable properties for object.

Allowable objects include:

• “Database Connection Objects” on page 5-95, which are created usingdatabase

• “Cursor Objects” on page 5-96, which are created using exec or fetch

• “Driver Objects” on page 5-97, which are created using driver

• “Database Metadata Objects” on page 5-97, which are created usingdmd

• “Drivermanager Objects” on page 5-97, which are created usingdrivermanager

• “Resultset Objects” on page 5-98, which are created using resultset

• “Resultset Metadata Objects” on page 5-98, which are created usingrsmd

If you call these objects from applications that use Oracle Java, you canget more information about object properties from the Java Web site:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/DatabaseMetaData.ht

5-94

Page 279: Database Toolbox™ II

get

Database Connection Objects

Allowable property names and returned values for database connectionobjects appear in the following table.

Property Value

'AutoCommit' Status of the AutoCommit flag. It is either on or off,as specified by set

'Catalog' Name of the catalog in the data source. You may needto extract a single catalog name from 'Catalog' forfunctions such as columns, which accept only a singlecatalog.

'Driver' Driver used for a JDBC connection, as specified bydatabase

'Handle' Identifies a JDBC connection object

'Instance' Name of the data source for an ODBC connection orthe name of a database for a JDBC connection, asspecified by database

'Message' Error message returned by database

'ReadOnly' 1 if the database is read only; 0 if the database iswritable

'TimeOut' Value for LoginTimeout

'TransactionIsolation' Value of current transaction isolation mode

'Type' Object type, specifically Database Object

'URL' For JDBC connections only, the JDBC URLobjectjdbc:subprotocol:subname, as specified bydatabase

'UserName' User name required to connect to a given database,as specified by database

'Warnings' Warnings returned by database

5-95

Page 280: Database Toolbox™ II

get

Cursor Objects

Allowable property names and returned values for cursor objects appearin the following table.

Property Value

'Attributes' Cursor attributes. This field is alwaysempty. Use the attr function to retrievecursor attributes.

'Data' Data in the cursor object data element (thequery results)

'DatabaseObject' Information about a given database object

'RowLimit' Maximum number of rows returned byfetch, as specified by set

'SQLQuery' SQL statement for a cursor, as specified byexec

'Message' Error message returned from exec or fetch

'Type' Object type, specifically Database CursorObject

'ResultSet' Resultset object identifier

'Cursor' Cursor object identifier

'Statement' Statement object identifier

Note If you specify a value (in seconds) forthe timeout argument, queries time outafter the time exceeds the given value.

'Fetch' 0 for cursor created using exec;fetchTheData for cursor created usingfetch

5-96

Page 281: Database Toolbox™ II

get

Driver Objects

Allowable property names and examples of values for driver objectsappear in the following table.

Property Example of Value

'MajorVersion' 1

'MinorVersion' 1001

Database Metadata Objects

Database metadata objects have many properties. Some allowableproperty names and examples of their values appear in the followingtable.

Property Example of Value

'Catalogs' {4x1 cell}

'DatabaseProductName' 'ACCESS'

'DatabaseProductVersion' '03.50.0000'

'DriverName' 'JDBC-ODBC Bridge (odbcjt32.dll)'

'MaxColumnNameLength' 64

'MaxColumnsInOrderBy' 10

'URL' 'jdbc:odbc:dbtoolboxdemo'

'NullsAreSortedLow' 1

Drivermanager Objects

Allowable property names and examples of values for drivermanagerobjects appear in the following table.

5-97

Page 282: Database Toolbox™ II

get

Property Example of Value

'Drivers' {'oracle.jdbc.driver.OracleDriver@1d8e09ef'[1x37 char]}

'LoginTimeout' 0

'LogStream' []

Resultset Objects

Allowable property names and examples of values for resultset objectsappear in the following table.

Property Example of Value

'CursorName' {'SQL_CUR92535700x''SQL_CUR92535700x'}

'MetaData' {1x2 cell}

'Warnings' {[] []}

Resultset Metadata Objects

Allowable property names and examples of values for a resultsetmetadata objects appear in the following table.

Property Example of Value

'CatalogName' {'' ''}

'ColumnCount' 2

'ColumnName' {'Calc_Date' 'Avg_Cost'}

'ColumnTypeName' {'TEXT' 'LONG'}

'TableName' {'' ''}

'isNullable' {[1] [1]}

'isReadOnly' {[0] [0]}

5-98

Page 283: Database Toolbox™ II

get

The empty strings for CatalogName and TableName indicate thatdatabases do not return these values.

For command-line help on get, use the overloaded methods:

help cursor/gethelp database/gethelp dmd/gethelp driver/gethelp drivermanager/gethelp resultset/gethelp rsmd/get

Examples Example 1 — Get Connection Property and Data SourceName

Connect to the database dbtoolboxdemo, and then get the name of thedata source for the connection and assign it to v.

conn = database('dbtoolboxdemo', '', '');v = get(conn, 'Instance')

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

Example 2 — Get Connection Property and AutoCommit FlagStatus

Check the status of the AutoCommit flag for the database connectionconn.

get(conn, 'AutoCommit')

ans =on

Example 3 — Display Data in Cursor

Display data in the cursor object curs by running:

curs = exec(conn, 'select productdescription from producttable')

5-99

Page 284: Database Toolbox™ II

get

curs = fetch(curs);get(curs, 'Data')

or:

curs.Data

ans =

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

Example 4 — Get Database Metadata Object Properties

1 View the properties of the database metadata object for connectionconn.

dbmeta = dmd(conn);

v = get(dbmeta)

v =

AllProceduresAreCallable: 1

AllTablesAreSelectable: 1

DataDefinitionCausesTransactionCommit: 1

DataDefinitionIgnoredInTransactions: 0

DoesMaxRowSizeIncludeBlobs: 0

Catalogs: {8x1 cell}

CatalogSeparator: '.'

CatalogTerm: 'DATABASE'

5-100

Page 285: Database Toolbox™ II

get

DatabaseProductName: 'ACCESS'

DatabaseProductVersion: '04.00.0000'

DefaultTransactionIsolation: 2

DriverMajorVersion: 2

DriverMinorVersion: 1

DriverName: 'JDBC-ODBC Bridge (ACEODBC.DLL)'

DriverVersion: '2.0001 (Microsoft Access database engine)'

ExtraNameCharacters: '~@#$%^&*_-+=\}{"';:?/><,.![]|'

IdentifierQuoteString: '`'

IsCatalogAtStart: 1

MaxBinaryLiteralLength: 255

MaxCatalogNameLength: 260

MaxCharLiteralLength: 255

MaxColumnNameLength: 64

MaxColumnsInGroupBy: 10

MaxColumnsInIndex: 10

MaxColumnsInOrderBy: 10

MaxColumnsInSelect: 255

MaxColumnsInTable: 255

MaxConnections: 64

MaxCursorNameLength: 64

MaxIndexLength: 255

MaxProcedureNameLength: 64

MaxRowSize: 4052

MaxSchemaNameLength: 0

MaxStatementLength: 65000

MaxStatements: 0

MaxTableNameLength: 64

MaxTablesInSelect: 16

MaxUserNameLength: 0

NumericFunctions: [1x73 char]

ProcedureTerm: 'QUERY'

Schemas: {}

SchemaTerm: ''

SearchStringEscape: '\'

SQLKeywords: [1x255 char]

StringFunctions: [1x91 char]

5-101

Page 286: Database Toolbox™ II

get

StoresLowerCaseIdentifiers: 0

StoresLowerCaseQuotedIdentifiers: 0

StoresMixedCaseIdentifiers: 0

StoresMixedCaseQuotedIdentifiers: 1

StoresUpperCaseIdentifiers: 0

StoresUpperCaseQuotedIdentifiers: 0

SystemFunctions: ''

TableTypes: {18x1 cell}

TimeDateFunctions: [1x111 char]

TypeInfo: {16x1 cell}

URL: 'jdbc:odbc:tutorial2'

UserName: 'admin'

NullPlusNonNullIsNull: 0

NullsAreSortedAtEnd: 0

NullsAreSortedAtStart: 0

NullsAreSortedHigh: 0

NullsAreSortedLow: 1

UsesLocalFilePerTable: 0

UsesLocalFiles: 1

2 To view names of the catalogs in the database, run:

v.Catalogsans =

'D:\matlab\toolbox\database\dbdemos\db1''D:\matlab\toolbox\database\dbdemos\origtutorial''D:\matlab\toolbox\database\dbdemos\tutorial''D:\matlab\toolbox\database\dbdemos\tutorial1'

See Also columns | fetch | database | dmd | driver | drivermanager | exec |getdatasources | resultset | rows | rsmd | set

5-102

Page 287: Database Toolbox™ II

getdatasources

Purpose Return names of ODBC and JDBC data sources on system

Syntax d = getdatasources

Description d = getdatasources returns the names of valid ODBC and JDBC datasources on the system as a cell array d of strings. The function getsthe names of ODBC data sources from the ODBC.INI file located in thefolder returned by running:

myODBCdir = getenv('WINDIR')

d is empty when the ODBC.INI file is valid, but no data sources aredefined. d equals -1 when the ODBC.INI file cannot be opened.

The function also retrieves the names of data sources that are in thesystem registry but not in the ODBC.INI file.

If you do not have write access to myODBCdir, the results ofgetdatasources may not include data sources that you recentlyadded. In this case, specify a temporary, writable, output folder via thepreference TempDirForRegistryOutput. For more information aboutthis preference, see setdbprefs.

getdatasources gets the names of JDBC data sources from the filethat you define using setdbprefs or the Define JDBC data sourcesdialog box.

Examples Get the names of databases on your system.

d = getdatasourcesd =

'MS Access Database' 'dbtoolboxdemo'

See Also database | get | setdbprefs

5-103

Page 288: Database Toolbox™ II

importedkeys

Purpose Return information about imported foreign keys

Syntax i = importedkeys(dbmeta, 'cata', 'sch')i = importedkeys(dbmeta, 'cata', 'sch', 'tab')

Description i = importedkeys(dbmeta, 'cata', 'sch') returns foreign importedkey information, that is, information about fields that reference primarykeys in other tables, in the schema sch, of the catalog cata, for thedatabase whose database metadata object is dbmeta.

i = importedkeys(dbmeta, 'cata', 'sch', 'tab') returns foreignimported key information in the table tab. In turn, fields in tabreference primary keys in other tables in the schema sch, of the catalogcata, for the database whose database metadata object is dbmeta.

Examples Get foreign key information for the schema SCOTT in the catalog orcl,for dbmeta.

i = importedkeys(dbmeta,'orcl','SCOTT')i =

Columns 1 through 7'orcl' 'SCOTT' 'DEPT' 'DEPTNO' 'orcl' ...'SCOTT' 'EMP'

Columns 8 through 13'DEPTNO' '1' 'null' '1' 'FK_DEPTNO'...'PK_DEPT'

The results show foreign imported key information as described in thefollowing table.

Column Description Value

1 Catalog containing primary key, referencedby foreign imported key

orcl

2 Schema containing primary key, referencedby foreign imported key

SCOTT

5-104

Page 289: Database Toolbox™ II

importedkeys

Column Description Value

3 Table containing primary key, referenced byforeign imported key

DEPT

4 Column name of primary key, referenced byforeign imported key

DEPTNO

5 Catalog that has foreign imported key orcl

6 Schema that has foreign imported key SCOTT

7 Table that has foreign imported key EMP

8 Foreign key column name, that is the columnname that references the primary key inanother table

DEPTNO

9 Sequence number within foreign key 1

10 Update rule, that is, what happens to theforeign key when the primary key updates

null

11 Delete rule, that is, what happens to theforeign key when the primary key is deleted

1

12 Foreign imported key name FK_DEPTNO

13 Primary key name in referenced table PK_DEPT

In the schema SCOTT, there is only one foreign imported key. The tableEMP contains a field, DEPTNO, that references the primary key in theDEPT table, the DEPTNO field.

EMP is the referencing table and DEPT is the referenced table.

DEPTNO is a foreign imported key in the EMP table. Reciprocally, theDEPTNO field in the table DEPT is an exported foreign key and theprimary key.

For a description of the codes for update and delete rules, see thegetImportedKeys property on the Oracle Java Web site:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/DatabaseMetaData

5-105

Page 290: Database Toolbox™ II

importedkeys

See Also crossreference | dmd | exportedkeys | get | primarykeys

5-106

Page 291: Database Toolbox™ II

indexinfo

Purpose Return indices and statistics for database tables

Syntax x = indexinfo(dbmeta, 'cata', 'sch', 'tab')

Description x = indexinfo(dbmeta, 'cata', 'sch', 'tab') returns indices andstatistics for the table tab, in the schema sch, of the catalog cata, forthe database whose database metadata object is dbmeta.

Examples Get index and statistics information for the table DEPT in the schemaSCOTT of the catalog orcl, for dbmeta.

x = indexinfo(dbmeta,'','SCOTT','DEPT')x =Columns 1 through 8'orcl' 'SCOTT' 'DEPT' '0' 'null' 'null' '0' '0''orcl' 'SCOTT' 'DEPT' '0' 'null' 'PK_DEPT' '1' '1'

Columns 9 through 13'null' 'null' '4' '1' 'null''DEPTNO' 'null' '4' '1' 'null'

The results contain two rows, meaning there are two index columns.The statistics for the first index column appear in the following table.

Column Description Value

1 Catalog orcl

2 Schema SCOTT

3 Table DEPT

4 Not unique: 0 if index values can benot unique, 1 otherwise

0

5 Index catalog null

6 Index name null

7 Index type 0

5-107

Page 292: Database Toolbox™ II

indexinfo

Column Description Value

8 Column sequence number withinindex

0

9 Column name null

10 Column sort sequence null

11 Number of rows in the index table ornumber of unique values in the index

4

12 Number of pages used for the table ornumber of pages used for the currentindex

1

13 Filter condition null

For more information about the index information, see thegetIndexInfo property on the Oracle Java Web site:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/DatabaseMetaData.ht

See Also dmd | get | tables

5-108

Page 293: Database Toolbox™ II

insert

Purpose Add MATLAB data to database tables

Syntax insert(conn,'tab',colnames,exdata)

Description insert(conn,'tab',colnames,exdata)

insert exports records from the MATLAB variable exdata into newrows in an existing database table tablename via the connection conn.The variable exdata can be a cell array, numeric matrix, table, dataset,or structure. You do not specify the type of data you are exporting;the data is exported in its current MATLAB format. Specify columnnames for tablename as strings in the MATLAB cell array colnames. Ifexdata is a structure, field names in the structure must exactly matchcolnames. If exdata is a table or a dataset, the variable names in thetable or dataset must exactly match colnames.

When working with a JDBC driver connection or a JDBC-ODBC bridgeconnection established using the database function, fastinsert offersimproved performance over insert. This is because insert createsand executes an SQL insert query for each row of data. fastinsertcreates the insert query only once and then allows for the data valuesto be plugged in. All rows of data get inserted as a batch resulting inan overall faster performance over insert. However, since fastinsertrelies more on driver functions compared to insert, it is possible insome edge case scenarios that the driver functions do not work asexpected. In such cases, insert might be preferred, especially if thedata to be inserted is small. datainsert is faster than fastinsert butneeds data to be formatted in a specific way and accepts cell arrays andnumeric matrices as input data.

When working with a native ODBC connection established using thedatabase.ODBCConnection function, fastinsert and insert areidentical. datainsert is not supported for native ODBC connections.

insert uses the same syntax as fastinsert.

5-109

Page 294: Database Toolbox™ II

insert

Notes:

• insert supports the native ODBC interface. To insert datesand timestamps with the native ODBC interface, use the format'YYYY-MM-DD HH:MM:SS.MS'.

• To insert data into a structure, table, or dataset, use the followingspecial formatting. Each field or variable in a structure, table, ordataset must be a cell array or double vector of size m*1, where m isthe number of rows to be inserted.

Examples Example 1 — Insert a Table Record Using Native ODBC

1 Create a connection conn using the native ODBC interface and thedbtoolboxdemo data source.

conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')

conn =

ODBCConnection with properties:

Instance: 'dbtoolboxdemo'UserName: 'admin'Message: []Handle: [1x1 database.internal.ODBCConnectHandle]

TimeOut: 0AutoCommit: 0

Type: 'ODBCConnection Object'

conn has an empty Message property, which means a successfulconnection.

2 Select and display the data from the productTable.

curs = exec(conn, 'select * from productTable');

5-110

Page 295: Database Toolbox™ II

insert

curs = fetch(curs);curs.Data

ans =

productNumber stockNumber supplierNumber unitCost pr------------- ----------- -------------- -------- -9 125970 1003 13 'V8 212569 1001 5 'T7 389123 1007 16 'E2 400314 1002 9 'P4 400339 1008 21 'S1 400345 1001 14 'B5 400455 1005 3 'T6 400876 1004 8 'S3 400999 1009 17 'S

10 888652 1006 24 'T

3 Store the column names of productTable in a cell array.

colnames = {'productNumber' 'stockNumber' 'supplierNumber' ...'unitCost' 'productDescription'};

4 Store the data for the insert in a cell array, exdata. The datacontains productNumber equal to 11, stockNumber equal to 400565,supplierNumber equal to 1010, unitCost equal to $10, andproductDescription equal to 'Rubik''s Cube'. Then, convert thecell array to a table, exdata_table.

exdata = {11, 400565, 1010, 10, 'Rubik''s Cube'};exdata_table = cell2table(exdata,'VariableNames',colnames)

exdata_table =

productNumber stockNumber supplierNumber unitCost pr------------- ----------- -------------- -------- -11 400565 1010 10 'R

5-111

Page 296: Database Toolbox™ II

insert

5 Insert the table data into the productTable.

insert(conn, 'productTable', colnames, exdata_table);

6 Display the data from the productTable again.

curs = exec(conn, 'select * from productTable');curs = fetch(curs);curs.Data

ans =

productNumber stockNumber supplierNumber unitCost produ------------- ----------- -------------- -------- -----9 125970 1003 13 'Vict8 212569 1001 5 'Trai7 389123 1007 16 'Engi2 400314 1002 9 'Pain4 400339 1008 21 'Spac1 400345 1001 14 'Buil5 400455 1005 3 'Tin6 400876 1004 8 'Sail3 400999 1009 17 'Slin

10 888652 1006 24 'Tedd11 400565 1010 10 'Rubi

A new row appears in the productTable with the data fromexdata_table.

Example 2— Insert the Contents of a Cell Array

1 Using the dbtoolboxdemo data source, select and display the datafrom the yearlySales table.

curs = exec(conn, 'select * from yearlySales');curs = fetch(curs);curs.Data

ans =

5-112

Page 297: Database Toolbox™ II

insert

Month salesTotal Revenue--------- ---------- -------'January' 130 1200'Feb' 25 250

2 Store the column names of yearlySales in a cell array.

colnames = {'Month' 'salesTotal' 'Revenue'};

3 Store the data for the insert in a cell array, exdata. The datacontains Month equal to 'March', salesTotal equal to $50, andRevenue equal to $2000.

exdata = {'March',50,2000};

4 Insert the data into the yearlySales table.

insert(conn, 'yearlySales', colnames, exdata);

5 Display the data from the yearlySales table again.

curs = exec(conn, 'select * from yearlySales');curs = fetch(curs);curs.Data

ans =

Month salesTotal Revenue--------- ---------- -------'January' 130 1200'Feb' 25 250'March' 50 2000

A new row appears in the yearlySales table with the data fromexdata.

See Also commit | fastinsert | querybuilder | rollback

5-113

Page 298: Database Toolbox™ II

insert

How To • “Using the Native ODBC Database Connection” on page 2-12

5-114

Page 299: Database Toolbox™ II

isconnection

Purpose Detect whether database connections are valid

Syntax a = isconnection(conn)

Description a = isconnection(conn) returns 1 if the database connection connis valid, or returns 0 otherwise.

Examples Check if the database connection conn is valid.

a = isconnection(conn)a =

1

See Also database | isreadonly | ping

5-115

Page 300: Database Toolbox™ II

isdriver

Purpose Detect whether driver is valid JDBC driver object

Syntax a = isdriver(d)

Description a = isdriver(d) returns 1 if d is a valid JDBC driver object. It returns0 otherwise.

Examples Check if d is a valid JDBC driver object.

a = isdriver(d)a =

1

See Also driver | get | isjdbc | isurl

5-116

Page 301: Database Toolbox™ II

isjdbc

Purpose Detect whether driver is JDBC compliant

Syntax a = isjdbc(d)

Description a = isjdbc(d) returns 1 if the driver object d is JDBC compliant. Itreturns 0 otherwise.

Examples Verify whether the database driver object d is JDBC compliant.

a = isjdbc(d)a =

1

See Also driver | get | isdriver | isurl

5-117

Page 302: Database Toolbox™ II

isnullcolumn

Purpose Detect whether last record read in resultset is NULL

Syntax a = isnullcolumn(rset)

Description a = isnullcolumn(rset) returns 1 if the last record read in theresultset rset is NULL. It returns 0 otherwise.

Examples Example 1 — Result Is Not NULL

isnullcolumn returns not null.

1 Run:

curs = fetch(curs,1);rset = resultset(curs);isnullcolumn(rset)ans =

0

2 Verify this result.

curs.Dataans =

[1400]

Example 2 — Result Is NULL

isnullcolumn returns null.

1 Run:

curs = fetch(curs,1);rset = resultset(curs);isnullcolumn(rset)ans =

1

2 Verify this result.

5-118

Page 303: Database Toolbox™ II

isnullcolumn

curs.Dataans =

[NaN]

See Also get | resultset

5-119

Page 304: Database Toolbox™ II

isreadonly

Purpose Detect whether database connection is read only

Syntax a = isreadonly(conn)

Description a = isreadonly(conn) returns 1 if the database connection conn isread only. It returns 0 otherwise.

Examples Check whether conn is read only.

a = isreadonly(conn)

The result indicates that the database connection conn is read only:

a =1

Therefore, you cannot run fastinsert, insert, or update functionson this database.

See Also database | isconnection

5-120

Page 305: Database Toolbox™ II

isurl

Purpose Detect whether database URL is valid

Syntax a = isurl(d, 's')

Description a = isurl(d, 's') returns 1 if the database URL s for the driverobject d is valid. It returns 0 otherwise.

The URL s is of the form jdbc:odbc:name or name.

Examples Check whether the database URLjdbc:odbc:thin:@144.212.123.24:1822: is valid for driver object d.

a = isurl(d, 'jdbc:odbc:thin:@144.212.123.24:1822:')a =

1

This indicates that the database URL is valid for d.

See Also driver | get | isdriver | isjdbc

5-121

Page 306: Database Toolbox™ II

logintimeout

Purpose Set or get time allowed to establish database connection

Syntax timeout = logintimeout('driver', time)timeout = logintimeout(time)timeout = logintimeout('driver')timeout = logintimeout

Description timeout = logintimeout('driver', time) sets the amount of time,in seconds, for a MATLAB session to connect to a database via agiven JDBC driver. Use logintimeout before running the databasefunction. If the MATLAB session cannot connect to the database withinthe specified time, it stops trying.

timeout = logintimeout(time) sets the amount of time, in seconds,allowed for a MATLAB session to try to connect to a database via anODBC connection. Use logintimeout before running the databasefunction. If the MATLAB session cannot connect within the allowedtime, it stops trying.

timeout = logintimeout('driver') returns the time, in seconds,that was previously specified for the JDBC driver. A returned value of0 means that the timeout value was not previously set. The MATLABsession stops trying to connect to the database if it is not immediatelysuccessful.

timeout = logintimeout returns the time, in seconds, that youpreviously specified for an ODBC connection. A returned value of 0means that the timeout value was not previously set; the MATLABsoftware session stops trying to make a connection if it is notimmediately successful.

Note If you do not specify a value for logintimeout and the MATLABsession cannot establish a database connection, your MATLAB sessionmay freeze.

5-122

Page 307: Database Toolbox™ II

logintimeout

Note Apple Mac OS platforms do not support logintimeout.

Examples Example 1 — Get Timeout Value for ODBC Connection

View the current connection timeout value.

logintimeoutans =

0

This indicates that you have not specified a timeout value.

Example 2 — Set Timeout Value for ODBC Connection

Set the timeout value to 5 seconds.

logintimeout(5)ans =

5

Example 3 — Get and Set Timeout Value for JDBC Connection

1 Check the timeout value for a database connection that is establishedusing an Oracle JDBC driver.

logintimeout('oracle.jdbc.driver.OracleDriver')ans =

0

This indicates that the timeout value is currently 0.

2 Set the timeout to 5 seconds.

timeout = ...logintimeout('oracle.jdbc.driver.OracleDriver', 5)timeout =

5

5-123

Page 308: Database Toolbox™ II

logintimeout

3 Verify the timeout value.

logintimeout('oracle.jdbc.driver.OracleDriver')ans =

5

See Also database | get | set

5-124

Page 309: Database Toolbox™ II

namecolumn

Purpose Map resultset column name to resultset column index

Syntax x = namecolumn(rset, n)

Description x = namecolumn(rset, n) maps a resultset column name n to itsresultset column index. rset is the resultset and n is a string or cellarray of strings containing the column names.

Examples 1 Get the indices for the column names DNAME and LOC resultset objectrset.

x = namecolumn(rset, {'DNAME';'LOC'})x =

2 3

The results show that DNAME is column 2 and LOC is column 3.

2 Get the index only for the LOC column.

x = namecolumn(rset, 'LOC')

See Also columnnames | resultset

5-125

Page 310: Database Toolbox™ II

ping

Purpose Get status information about database connection

Syntax ping(conn)

Description ping(conn) returns status information about the database connectionconn if the connection is open. It returns an error message otherwise.

Examples Example 1 — Get Status Information About ODBC Connection

Check the status of the ODBC connection conn.

ping(conn)ans =

DatabaseProductName: 'ACCESS'DatabaseProductVersion: '03.50.0000'

JDBCDriverName: 'JDBC-ODBC Bridge (odbcjt32.dll)'JDBCDriverVersion: '1.1001 (04.00.4202)'

MaxDatabaseConnections: 64CurrentUserName: 'admin'

DatabaseURL: 'jdbc:odbc:dbtoolboxdemo'AutoCommitTransactions: 'True'

Example 2 — Get Status Information About JDBC Connection

Check the status of the JDBC connection conn.

ping(conn)ans =

DatabaseProductName: 'Oracle'DatabaseProductVersion: [1x166 char]

JDBCDriverName: 'Oracle JDBC driver'JDBCDriverVersion: '7.3.4.0.2'

MaxDatabaseConnections: 0CurrentUserName: 'scott'

DatabaseURL: 'jdbc:oracle:thin: [email protected]:1822:orcl'AutoCommitTransactions:'True'

5-126

Page 311: Database Toolbox™ II

ping

Example 3 — Unsuccessful Request for Information AboutConnection

In this example, the database connection conn has been terminatedor is not successful.

ping(conn)Cannot Ping the Database Connection

See Also database | dmd | get | isconnection | set | supports

5-127

Page 312: Database Toolbox™ II

primarykeys

Purpose Get primary key information for database table or schema

Syntax k = primarykeys(dbmeta, 'cata', 'sch')k = primarykeys(dbmeta, 'cata', 'sch', 'tab')

Description k = primarykeys(dbmeta, 'cata', 'sch') returns primary keyinformation for all tables in the schema sch, of the catalog cata, for thedatabase whose database metadata object is dbmeta.

k = primarykeys(dbmeta, 'cata', 'sch', 'tab') returns primarykey information for the table tab, in the schema sch, of the catalogcata, for the database whose database metadata object is dbmeta.

Examples Get primary key information for the DEPT table:

k = primarykeys(dbmeta,'orcl','SCOTT','DEPT')k =

'orcl' 'SCOTT' 'DEPT' 'DEPTNO' '1' 'PK_DEPT'

5-128

Page 313: Database Toolbox™ II

primarykeys

The results show the primary key information as described in thefollowing table.

Column Description Value

1 Catalog orcl

2 Schema SCOTT

3 Table DEPT

4 Column name of primarykey

DEPTNO

5 Sequence number withinprimary key

1

6 Primary key name PK_DEPT

See Also crossreference | dmd | exportedkeys | get | importedkeys

5-129

Page 314: Database Toolbox™ II

procedurecolumns

Purpose Get stored procedure parameters and result columns of catalogs

Syntax pc = procedurecolumns(dbmeta, 'cata', 'sch')pc = procedurecolumns(dbmeta, 'cata')

Description pc = procedurecolumns(dbmeta, 'cata', 'sch') returns the storedprocedure parameters and result columns for the schema sch, of thecatalog cata, for the database whose database metadata object isdbmeta.

pc = procedurecolumns(dbmeta, 'cata') returns stored procedureparameters and result columns for the catalog cata, for the databasewhose database metadata object is dbmeta.

Running the stored procedure generates results. One row is returnedfor each column.

Examples Get stored procedure parameters for the schema ORG, in the catalogtutorial, for the database metadata object dbmeta:

pc = procedurecolumns(dbmeta,'tutorial', 'ORG')pc =

Columns 1 through 7[1x19 char] 'ORG' 'display' 'Month' '3' ...'12' 'TEXT'[1x19 char] 'ORG' 'display' 'Day' '3' ...'4' 'INTEGER'

Columns 8 through 13'50' '50' 'null' 'null' '1' 'null''50' '4' 'null' 'null' '1' 'null'

The results show stored procedure parameter and result information.Because two rows of data are returned, there are two columns of datain the results. The results show that running the stored proceduredisplay returns the Month and Day columns.

5-130

Page 315: Database Toolbox™ II

procedurecolumns

Following is a full description of the procedurecolumns results for thefirst row (Month).

Column Description Value for First Row

1 Catalog 'D:\orgdatabase\orcl'

2 Schema 'ORG'

3 Procedure name 'display'

4 Column/parameter name 'MONTH'

5 Column/parameter type '3'

6 SQL data type '12'

7 SQL data type name 'TEXT'

8 Precision '50'

9 Length '50'

10 Scale 'null'

11 Radix 'null'

12 Nullable '1'

13 Remarks 'null'

For more information about the procedurecolumns results, see thegetProcedureColumns property on the Oracle Java Web site:

http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/DatabaseMetaData

See Also dmd | get | procedures

5-131

Page 316: Database Toolbox™ II

procedures

Purpose Get stored procedures for catalogs

Syntax p = procedures(dbmeta, 'cata')p = procedures(dbmeta, 'cata', 'sch')

Description p = procedures(dbmeta, 'cata') returns stored procedures in thecatalog cata for the database whose database metadata object is dbmeta.

p = procedures(dbmeta, 'cata', 'sch') returns the storedprocedures in the schema sch, of the catalog cata, for the databasewhose database metadata object is dbmeta.

Stored procedures are SQL statements that are saved with thedatabase. Use the exec function to run a stored procedure. Specifythe stored procedure as the sqlquery argument instead of explicitlyentering the sqlquery statement as the argument.

Examples Get the names of stored procedures for the catalog DBA for the databasemetadata object dbmeta:

p = procedures(dbmeta,'DBA')p =

'sp_contacts''sp_customer_list''sp_customer_products''sp_product_info''sp_retrieve_contacts''sp_sales_order'

Execute the stored procedure sp_customer_list for the databaseconnection conn, and fetch all data:

curs = exec(conn,'sp_customer_list');curs = fetch(conn)curs =

Attributes: []Data: {10x2 cell}

DatabaseObject: [1x1 database]

5-132

Page 317: Database Toolbox™ II

procedures

RowLimit: 0SQLQuery: 'sp_customer_list'Message: []

Type: 'Database Cursor Object'ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: ...[1x1 com.mathworks.toolbox.database.sqlExec]

Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]Fetch: ...

[1x1 com.mathworks.toolbox.database.fetchTheData]

View the results:

curs.Dataans =

[101] 'The Power Group'[102] 'AMF Corp.'[103] 'Darling Associates'[104] 'P.S.C.'[105] 'Amo & Sons'[106] 'Ralston Inc.'[107] 'The Home Club'[108] 'Raleigh Co.'[109] 'Newton Ent.'[110] 'The Pep Squad'

See Also dmd | exec | get | procedurecolumns

5-133

Page 318: Database Toolbox™ II

querybuilder

Purpose Start SQL query builder GUI to import and export data

Compatibility querybuilder is not recommended. Use dexplore instead.

Syntax querybuilder

Description querybuilder starts Visual Query Builder (VQB), which is theDatabase Toolbox GUI.

Tip To populate the VQB Schema and Catalog fields, you mustassociate your user name with schemas or catalogs before starting VQB.

Examples For more information on Visual Query Builder, including examples, seethe VQB Help menu or “Getting Started with Visual Query Builder”on page 3-2.

5-134

Page 319: Database Toolbox™ II

querytimeout

Purpose Get time specified for SQL queries to succeed

Syntax timeout = querytimeout(curs)

Description timeout = querytimeout(curs) returns the amount of time, inseconds, allowed for SQL queries of the open cursor curs to succeed. Ifa given query cannot complete in the specified time, the toolbox stopstrying to perform the query.

The database administrator defines timeout values. If the timeoutvalue is zero, queries must complete immediately.

Examples Get the current database timeout setting for curs.

querytimeout(curs)ans =

10

Limitations • If a given database does not have a database timeout feature, itreturns the following:

[Driver]Driver not capable

• ODBC drivers for Microsoft Access and Oracle do not supportquerytimeout.

See Also exec

5-135

Page 320: Database Toolbox™ II

register

Purpose Load database driver

Syntax register(d)

Description register(d) loads the database driver object d. Use unregister tounload the driver.

Although database automatically loads a driver, register allows youto use get to view properties of the driver before connecting to thedatabase. The register function also allows you to run drivermanagerwith set and get on properties for loaded drivers.

Examples 1 register(d) loads the database driver object d.

2 get(d) returns properties of the driver object.

See Also driver | drivermanager | get | set | unregister

5-136

Page 321: Database Toolbox™ II

resultset

Purpose Construct resultset object

Syntax rset = resultset(curs)

Description rset = resultset(curs) creates a resultset object rset for the cursorcurs. To get properties of rset, create a resultset metadata object usingrsmd, or make calls to rset using applications based on Oracle Java.

Run clearwarnings, isnullcolumn, and namecolumn on rset. Useclose to close the resultset, which frees up resources.

Examples Construct a resultset object rset.

rset = resultset(curs)rset =

Handle: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

See Also clearwarnings | close | fetch | exec | get | isnullcolumn |namecolumn | rsmd

5-137

Page 322: Database Toolbox™ II

rollback

Purpose Undo database changes

Syntax rollback(conn)

Description rollback(conn) reverses changes made to a database usingfastinsert, insert, or update via the database connection conn. Therollback function reverses all changes made since the last commit orrollback operation. To use rollback, the AutoCommit flag for connmust be off.

Note rollback does not roll back data in MySQL databases if thedatabase engine is not InnoDB.

Examples 1 Ensure that the AutoCommit flag for connection conn is off byrunning:

get(conn,'AutoCommit')ans =off

2 Insert data contained in exdata into the columns DEPTNO, DNAME, andLOC, in the table DEPT, for the data source conn.

fastinsert(conn, 'DEPT', ...{'DEPTNO';'DNAME';'LOC'}, exdata)

3 Roll back the data that you inserted into the database by running:

rollback(conn)

The data in exdata is removed from the database. The database nowcontains the data it had before you ran the fastinsert function.

See Also commit | database | exec | fastinsert | get | insert | update

5-138

Page 323: Database Toolbox™ II

rows

Purpose Return number of rows in fetched data set

Syntax numrows = rows(curs)

Description numrows = rows(curs) returns the number of rows in the fetched dataset curs, where curs has been generated by the fetch function.

Examples There are four rows in the fetched data set curs.

numrows = rows(curs)

numrows =4

To see the four rows of data in curs, run:

curs.Dataans =

'Germany''Mexico''France''Canada'

See Also cols | fetch | get | rsmd

5-139

Page 324: Database Toolbox™ II

rsmd

Purpose Construct resultset metadata object

Syntax rsmeta = rsmd(rset)

Description rsmeta = rsmd(rset) creates a resultset metadata object rsmeta, forthe resultset object rset. Get properties of rsmeta using get or makecalls to rsmeta using applications that are based on Oracle Java.

Examples Create a resultset metadata object rsmeta.

rsmeta=rsmd(rset)rsmeta =

Handle: [1x1 sun.jdbc.odbc.JdbcOdbcResultSetMetaData]

Use v = get(rsmeta) and v.property to view properties of theresultset metadata object.

See Also exec | get | resultset

5-140

Page 325: Database Toolbox™ II

runsqlscript

Purpose Run SQL script on a database

Syntax results = runsqlscript(connect,sqlfilename)results = runsqlscript(connect,sqlfilename,Name,Value)

Description results = runsqlscript(connect,sqlfilename) runs the SQLcommands in the file sqlfilename on the connected database, andreturns a cursor array.

results = runsqlscript(connect,sqlfilename,Name,Value) usesadditional options specified by one or more Name,Value pairs.

InputArguments

connect - Database connectionconnection object

Database connection, specified as a connection object.

sqlfilename - File name of SQL commandsstring

File name of SQL commands to run, specified as a string. The filemust be a text file, and can contain comments along with SQL queries.Single line comments must start with --. Multiline comments shouldbe wrapped in /*...*/.

Example: 'C:\work\sql_file.sql'

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments.Name is the argument name and Value is the correspondingvalue. Name must appear inside single quotes (' '). You canspecify several name and value pair arguments in any order asName1,Value1,...,NameN,ValueN.

Example: 'RowInc',3,'QTimeOut',60 specifies that results bereturned in increments of three rows and the query time out in 60seconds

5-141

Page 326: Database Toolbox™ II

runsqlscript

’rowInc’ - Row limit0 implies all rows (default) | positive scalar

Row limit indicating the number of rows to retrieve at a time, specifiedas the comma-separated pair consisting of 'rowInc' and a positivescalar value. Use rowInc when importing large amounts of data.Retrieving data in increments helps reduce overall retrieval time.

Example: 'rowInc',5

Data Typesdouble

’QTimeOut’ - Query time out0 implies unlimited time (default) | positive scalar

Query time out (in seconds), specified as the comma-separated pairconsisting of 'QTimeOut' and a positive scalar value.

Example: 'QTimeOut',180

Data Typesdouble

OutputArguments

results - Query resultscursor array

Query results from executing the SQL commands, returned as a cursorarray. The number of elements in results is equal to the number ofbatches in the file sqlfilename.

results(M) contains the results from executing the Mth SQL batchin the SQL script. If the batch returns a resultset, it is stored inresults(M).Data.

Limitations • Use runsqlscript to import data into MATLAB, especially if thedata is the result of long and complex SQL queries that are difficultto convert into MATLAB strings. runsqlscript is not designed tohandle SQL scripts containing continuous PL/SQL blocks with BEGINand END, such as stored procedure definitions, trigger definitions, andso on. However, table definitions do work.

5-142

Page 327: Database Toolbox™ II

runsqlscript

• An SQL script containing any of the following can produce unexpectedresults:

- Apostrophes that are not escaped (including those in comments).For example, the string 'Here's the code' should be writtenas 'Here''s the code'.

- Nested comments.

Examples Run SQL Script

Run SQL commands from a file on a connected data source.

To run this example, set up the data source, dbtoolboxdemo,by following the steps in “Set Up the dbtoolboxdemo DataSource”. To get the file of SQL commands, navigate to\toolbox\database\dbdemos\compare_sales.sql in your MATLABroot folder, or copy and paste the path into your current workingdirectory.

Create the connection object to the data source, dbtoolboxdemo.

conn = database('dbtoolboxdemo','','');

User names and passwords are not required for this connection.

Run the SQL script, compare_sales.sql.

results = runsqlscript(conn,'compare_sales.sql')

results =

1x2 array of cursor objects

The SQL script has two queries, and returns two results when executed.

Display the results for the second query.

results(2)

ans =

5-143

Page 328: Database Toolbox™ II

runsqlscript

Attributes: []

Data: {4x6 cell}

DatabaseObject: [1x1 database]

RowLimit: 0

SQLQuery: [1x309 char]

Message: ''

Type: 'Database Cursor Object'

ResultSet: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]

Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

Display the resultset returned for the second query.

results(2).Data

ans =

'Painting Set' 'Terrific Toys' 'London' [3000] [2400] [1800]

'Victorian Doll' 'Wacky Widgets' 'Adelaide' [1400] [1100] [ 981]

'Sail Boat' 'Incredible Machines' 'Dublin' [3000] [2400] [1500]

'Slinky' 'Doll's Galore' 'London' [3000] [1500] [1000]

Get the column names for the data returned by the second query.

names = columnnames(results(2))

names =

'productDescription','supplierName','city','Jan_Sales','Feb_Sales','Mar_Sales'

Close the cursor array and connection.

close(results);close(conn);

5-144

Page 329: Database Toolbox™ II

runsqlscript

Run SQL Script in Row Increments

Run SQL commands from a file on a connected data source in two-rowincrements.

To run this example, set up the data source, dbtoolboxdemo,by following the steps in “Set Up the dbtoolboxdemo DataSource”. To get the file of SQL commands, navigate to\toolbox\database\dbdemos\compare_sales.sql in your MATLABroot folder, or copy and paste the path into your current workingdirectory.

Create the connection object to the data source, dbtoolboxdemo.

conn = database('dbtoolboxdemo','','');

User names and passwords are not required for this connection.

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

Run the SQL script, compare_sales.sql, specifying two-rowincrements.

results = runsqlscript(conn,'compare_sales.sql','rowInc',2)

results =

1x2 array of cursor objects

The SQL script has two queries, and returns two results when executed.

Display the resultset returned for the second query.

results(2).Data

ans =

'Painting Set' 'Terrific Toys' 'London' [3000] [2400] [1800]

'Victorian Doll' 'Wacky Widgets' 'Adelaide' [1400] [1100] [ 981]

5-145

Page 330: Database Toolbox™ II

runsqlscript

Only the first two rows of the results are returned.

Fetch the next increment of two rows.

res2 = fetch(results(2),2);res2.Data

ans =

'Sail Boat' 'Incredible Machines' 'Dublin' [3000] [2400] [1500]

'Slinky' 'Doll's Galore' 'London' [3000] [1500] [1000]

Close the cursor arrays and connection.

close(results);close(res2);close(conn);

Run SQL Script to Fetch Data in Batches

Run SQL commands from a file on a connected data source withautomated batching. Use this method to avoid Java heap memoryissues when the SQL script returns a large amount of data.

To run this example, set up the data source, dbtoolboxdemo,by following the steps in “Set Up the dbtoolboxdemo DataSource”. To get the file of SQL commands, navigate to\toolbox\database\dbdemos\compare_sales.sql in your MATLABroot folder, or copy and paste the path into your current workingdirectory.

Create the connection object to the data source, dbtoolboxdemo.

conn = database('dbtoolboxdemo','','');

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

Turn on batching for fetch.

5-146

Page 331: Database Toolbox™ II

runsqlscript

setdbprefs('FetchInBatches', 'yes')

Set appropriate batch size depending on the size of the resultset youexpect to fetch. For example, if you expect about a 100,000 rows in theoutput, a batch size of 10,000 is a good starting point. The larger theFetchBatchSize value, the fewer trips between Java and MATLAB, andthe memory consumption is greater for each batch. The optimal valuefor FetchBatchSize is decided based on several factors like the size perrow being retrieved, the Java heap memory value, the driver’s defaultfetch size, and system architecture, and hence, may vary from site tosite. For more information on estimating a value for FetchBatchSize,see “Preference Settings for Large Data Import” on page 3-10.

setdbprefs('FetchBatchSize', '2')

Run the SQL script, compare_sales.sql.

results = runsqlscript(conn, 'compare_sales.sql')

results =

1x2 array of cursor objects

Batching occurs internally within fetch, in that it fetches in incrementsof two rows at a time. The batching preferences are applied to all thequeries in the SQL script.

Tips • Any values assigned to rowInc or QTimeOut apply to all queries inthe SQL script. For example, if rowInc is set to 5, then all queries inthe script return at most five rows in their respective resultsets.

• You can set preferences for the resultsets using setdbprefs.Preference settings apply to all queries in the SQL script. Forexample, if the DataReturnFormat is set to numeric, all theresultsets return as numeric matrices.

5-147

Page 332: Database Toolbox™ II

runsqlscript

Definitions Batch

One or more SQL statements terminated by either a semicolon or thekeyword GO.

See Also resultset | setdbprefs | fetch

RelatedExamples

• “Set Up the dbtoolboxdemo Data Source”

Concepts • “Preference Settings for Large Data Import” on page 3-10

5-148

Page 333: Database Toolbox™ II

runstoredprocedure

Purpose Call stored procedure with input and output parameters

Syntax results = runstoredprocedure(conn, sp_name, parms_in,types_out)

Description results = runstoredprocedure(conn, sp_name, parms_in,types_out) calls a stored procedure with specified input parametersand returns output parameters, for the database connection handleconn . sp_name is the stored procedure to run, parms_in is a cellarray containing the input parameters for the stored procedure, andtypes_out is the list of data types for the output parameters.

Use runstoredprocedure to return the value of a variable to aMATLAB variable, which you cannot do when running a storedprocedure via exec. Running a stored procedure via exec returnsresultsets but cannot return output parameters.

Examples These examples illustrate how runstoredprocedure differs fromrunning stored procedures via exec.

1 Run a stored procedure that has no input or output parameters:

x = runstoredprocedure(c,'myprocnoparams')

2 Run a stored procedure given input parameters 2500 and 'Jones'with no output parameters.

x = runstoredprocedure(c,'myprocinonly',{2500,'Jones'})

3 Run the stored procedure myproc given input parameters2500 and 'Jones'. Return an output parameter of typejava.sql.Types.NUMERIC, which could be any numeric Oracle Javadata type. The output parameter x is the value of a database variablen. The stored procedure myproc creates this variable, given the inputvalues 2500 and 'Jones'. For example, myproc computes n, thenumber of days when Jones is 2500. It then returns the value ofn to x.

5-149

Page 334: Database Toolbox™ II

runstoredprocedure

x = runstoredprocedure(c,'myproc',{2500,'Jones'},{java.sql.Types.NUMERIC})

See Also fetch | exec

5-150

Page 335: Database Toolbox™ II

set

Purpose Set properties for database, cursor, or drivermanager object

Syntax set(object, 'property', value)set(object)

Description set(object, 'property', value) sets the value of property to valuefor the specified object.

set(object) displays all properties for object.

Allowable values for object are:

• “Database Connection Objects” on page 5-152, created usingdatabase

• “Cursor Objects” on page 5-153, created using exec or fetch

• “Drivermanager Objects” on page 5-153, created usingdrivermanager

You cannot set all of these properties for all databases. You receive anerror message when you try to set a property that the database doesnot support.

5-151

Page 336: Database Toolbox™ II

set

Database Connection Objects

The allowable values for property and value for a database connectionobject appear in the following table.

Property Value Description

'on' Database data is writtenand automatically committedwhen you run fastinsert,insert, or exec. You cannotuse rollback to reverse thisprocess.

'AutoCommit'

'off' Database data is notcommitted automaticallywhen you run fastinsert,insert, or update. Userollback to reverse thisprocess. When you are surethat your data is correct, usethe commit function to commitit to the database.

0 Not read only; that is,writable

'ReadOnly'

1 Read only

'TransactionIsolation' positiveinteger

Current transaction isolationlevel

Note For some databases, if you insert data and then close thedatabase connection without committing the data to the database, thedata gets committed automatically. Your database administrator cantell you whether your database behaves this way.

5-152

Page 337: Database Toolbox™ II

set

Cursor Objects

The allowable property and value for a cursor object appear in thefollowing table.

Property Value Description

'RowLimit' positiveinteger

Sets the RowLimit for fetch.Specify this property instead ofpassing RowLimit as an argumentto the fetch function. Whenyou define RowLimit for fetchby using set, fetch behavesdifferently depending on whattype of database you are using.

Drivermanager Objects

The allowable property and value for a drivermanager object appearin the following table.

Property Value Description

'LoginTimeout' positive integer Sets the logintimeoutvalue for all loadeddatabase drivers.

For command-line help on set, use the overloaded methods:

help cursor/sethelp database/sethelp drivermanager/set

Examples Example 1 — Set RowLimit for Cursor

This example does the following:

• Establishes a JDBC connection to a data source.

• Runs fetch to retrieve data from the table EMP.

5-153

Page 338: Database Toolbox™ II

set

• Sets RowLimit to 5.

conn=database('orcl','scott','tiger',...

'oracle.jdbc.driver.OracleDriver',...

'jdbc:oracle:thin:@144.212.123.24:1822:');

curs=exec(conn,'select * from EMP');

set(curs,'RowLimit',5)

curs=fetch(curs)

curs =

Attributes: []

Data: {5x8 cell}

DatabaseObject: [1x1 database]

RowLimit: 5

SQLQuery: 'select * from EMP'

Message: []

Type: 'Database Cursor Object'

ResultSet: [1x1 oracle.jdbc.driver.OracleResultSet]

Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]

Statement: [1x1 oracle.jdbc.driver.OracleStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

The RowLimit property of curs is 5 and the Data property is 5x8 cell,indicating that fetch returned five rows of data.

In this example, RowLimit limits the maximum number of rows you canretrieve. Therefore, rerunning the fetch function returns no data.

5-154

Page 339: Database Toolbox™ II

set

Example 2 — Set the AutoCommit Flag to On

This example shows what happens when you run a database updatefunction on a database whose AutoCommit flag is set to on.

1 Determine the status of the AutoCommit flag for the databaseconnection conn.

get(conn, 'AutoCommit')

ans =off

The flag is off.

2 Set the flag status to on and verify its value.

set(conn, 'AutoCommit', 'on');get(conn, 'AutoCommit')

ans =on

3 Insert a cell array exdata into column names colnames in the tableGrowth.

fastinsert(conn, 'Growth', colnames, exdata)

The data is inserted and committed to the database.

5-155

Page 340: Database Toolbox™ II

set

Example 3 — Set the AutoCommit Flag to Off and CommitData

This example shows the results of running fastinsert and commit toinsert and commit data into a database whose AutoCommit flag is off.

1 First set the AutoCommit flag to off for database connection conn.

set(conn, 'AutoCommit', 'off');

2 Insert a cell array exdata into the column names colnames in thetable Avg_Freight_Cost.

fastinsert(conn, 'Avg_Freight_Cost', colnames, exdata)

3 Commit the data to the database.

commit(conn)

Example 4 — Set the AutoCommit Flag to Off and Roll BackData

This example runs update to insert data into a database whoseAutoCommit flag is off. It then uses rollback to roll back the data.

1 Set the AutoCommit flag to off for database connection conn.

set(conn, 'AutoCommit', 'off');

2 Update the data in colnames in the Avg_Freight_Weight table, forthe record selected by whereclause, with data from the cell arrayexdata.

update(conn, 'Avg_Freight_Weight', colnames, exdata,whereclause)

3 Roll back the data.

rollback(conn)

5-156

Page 341: Database Toolbox™ II

set

The data in the table is now as it was before you ran update.

Example 5 — Set the LoginTimeout for a DrivermanagerObject

1 Create a drivermanager object dm and set its LoginTimeout value to3 seconds.

dm = drivermanager;set(dm,'LoginTimeout',3);

2 Verify this result.

logintimeoutans =

3

See Also fetch | database | drivermanager | exec | fastinsert | get |insert | logintimeout | ping | update

5-157

Page 342: Database Toolbox™ II

setdbprefs

Purpose Set preferences for retrieval format, errors, NULLs, and more

Alternative • From the Database Explorer Toolstrip, select Preferences to openthe Database Toolbox Preferences dialog box.

Syntax setdbprefss = setdbprefssetdbprefs('property')setdbprefs('property', 'value')setdbprefs({'property1'; ...}, {'value1'; ...})setdbprefs(s)

Description setdbprefs returns current values for database preferences.

s = setdbprefs returns current values for database preferences tothe structure s.

setdbprefs('property') returns the current value for the specifiedproperty.

setdbprefs('property', 'value') sets the specified property tovalue.

setdbprefs({'property1'; ...}, {'value1'; ...}) sets propertiesstarting with property1 to values starting with value1.

setdbprefs(s) sets preferences specified in the structure s to valuesthat you specify.

Allowable properties appear in the following tables:

• DataReturnFormat and ErrorHandling Properties and Values forsetdbprefs on page 5-159

• Null Data Handling Properties and Values for setdbprefs on page5-160

• Other Properties and Values for setdbprefs (Not Accessible via Query> Preferences) on page 5-162

5-158

Page 343: Database Toolbox™ II

setdbprefs

DataReturnFormat and ErrorHandling Properties and Values for setdbprefs

Property Allowable Values Description

'cellarray'(default), 'table','dataset','numeric', or'structure'

Format for data to import into the MATLABworkspace. Set the format based on thetype of data being retrieved, memoryconsiderations, and your preferred methodof working with retrieved data.

'cellarray'(default)

Import nonnumeric data into MATLAB cellarrays.

'table' Import data into MATLAB table objects.Use for all data types. Facilitates workingwith returned columns.

'dataset' Import data into MATLAB dataset objects.Use for all data types. Facilitates workingwith returned columns. This option requiresStatistics Toolbox.

'numeric' Import data into MATLAB matrix ofdoubles. Nonnumeric data types areconsidered NULL and appear as specified inthe NullNumberRead property. Use onlywhen data to retrieve is in numeric format,or when nonnumeric data to retrieve is notrelevant.

'DataReturnFormat'

'structure' Import data into a MATLAB structure. Usefor all data types. Facilitates working withreturned columns.

5-159

Page 344: Database Toolbox™ II

setdbprefs

DataReturnFormat and ErrorHandling Properties and Values for setdbprefs(Continued)

Property Allowable Values Description

'store' (default),'report', or'empty'

Specify how to handle errors when importingdata. Set this parameter before you runexec.

'store' (default) Errors from running database are stored inthe Message field of the returned connectionobject. Errors from running exec are storedin the Message field of the returned cursorobject.

'report' Errors from running database or execappear immediately in the MATLABCommand Window.

'ErrorHandling'

'empty' Errors from running database are stored inthe Message field of the returned connectionobject. Errors from running exec are storedin the Message field of the returned cursorobject. Objects that cannot be created arereturned as empty handles ([ ]).

Null Data Handling Properties and Values for setdbprefs

Property Allowable Values Description

'NullNumberRead' User-specified, forexample, '0'

Specify how NULL numbers appear after beingimported from a database into the MATLABworkspace. NaN is the default value. Stringvalues such as 'NULL' cannot be set if

5-160

Page 345: Database Toolbox™ II

setdbprefs

Null Data Handling Properties and Values for setdbprefs (Continued)

Property Allowable Values Description

'DataReturnFormat' is set to 'numeric'.Set this parameter before running fetch.

'NullNumberWrite' User-specified, forexample, 'NaN'(default)

Numbers in the specified format, forexample, NaN appears as NULL after beingexported from the MATLAB workspace to adatabase.

'NullStringRead' User-specified, forexample, 'null'(default)

Specify how NULL strings appear after beingimported from a database into the MATLABworkspace. Set this parameter beforerunning fetch.

'NullStringWrite' User-specified, forexample, 'null'(default)

Strings in the specified format, for example,'NULL', appear as NULL after being exportedfrom the MATLAB workspace to a database.

5-161

Page 346: Database Toolbox™ II

setdbprefs

Other Properties and Values for setdbprefs (Not Accessible via Query >Preferences)

PropertyAllowableValues Description

'JDBCDataSourceFile' User-specified,for example,'D:/file.mat'

Path to MAT-file containing JDBCdata sources. For more information,see “Accessing Existing JDBC DataSources” on page 2-4.

'UseRegistryForSources' 'yes' (default)or 'no'

When set to yes, VQB searches theMicrosoft Windows registry for ODBCdata sources that are not uncovered inthe system ODBC.INI file. The followingmessage might appear: Registryediting has been disabled by youradministrator. This message isharmless and can safely be ignored.

'TempDirForRegistryOutput' User-specified,for example,'D:/work'

Folder where VQB writes ODBC registrysettings when you run getdatasources.Use when you add data sources anddo not have write access to theMATLAB Current Folder. The defaultis the Windows temporary folder,which is returned by the commandgetenv('temp')).

If you specify a folder to which you donot have write access or which does notexist, the following error appears:

Cannot export<folder-name>\ODBC.INI:Error opening the file.There may be a diskor file system error.

5-162

Page 347: Database Toolbox™ II

setdbprefs

Other Properties and Values for setdbprefs (Not Accessible via Query >Preferences) (Continued)

PropertyAllowableValues Description

'DefaultRowPreFetch' User-specifiednumeric value,default value is'10000'

Number of rows fetched from theDatabase server at a time for any query.The higher the number, the fewer thenumber of trips to the server. Thissetting is applicable only for databasesthat allow this number to be set, e.g,Oracle.

'FetchInBatches' 'yes' or 'no'(default)

Automates fetching in batches for largedata sets where you might run intoJava heap memory errors in MATLAB.When the value is 'yes', fetch andrunsqlscript import the data inbatches in size of 'FetchBatchSize'.For an example, see fetch.

'FetchBatchSize' User-specifiednumeric value,default valueis '1000'Supportedvalues arefrom 1000 to1000000.

Automates fetching in batches for largedata sets when used in conjunction with'FetchInBatches'. When the valueof 'FetchInBatches' is 'yes', fetchand runsqlscript import the data inbatches in size of 'FetchBatchSize'.

For an example, see fetch. Formore information on estimatinga 'FetchBatchSize' value, see“Preference Settings for Large DataImport” on page 3-10.

5-163

Page 348: Database Toolbox™ II

setdbprefs

Tips • Preferences are retained across MATLAB sessions.

• Regardless of the value of 'NullNumberWrite', a NULL value isalways written to the database when you input [] or NaN for anumeric data type.

• For string inputs, a NULL value is written to the database only whenthe input value matches the value of 'NullStringWrite'.

Examples Example 1 — Display Current Values

Run setdbprefs.

setdbprefs

DataReturnFormat: 'cellarray'ErrorHandling: 'store'

NullNumberRead: '0'NullNumberWrite: 'NaN'NullStringRead: 'null'

NullStringWrite: 'null'JDBCDataSourceFile: 'C:\hold_x\jdbcConfig_test.mat'

UseRegistryForSources: 'yes'TempDirForRegistryOutput: 'C:\Work'

DefaultRowPreFetch: '10000'FetchInBatches: 'no'FetchBatchSize: '1000'

These values show that:

• Data is imported from databases into MATLAB cell arrays.

• Errors that occur during a database connection or SQL query attemptare stored in the Message field of the connection or cursor data object.

• Each NULL number in the database is read into the MATLABworkspace as NaN. Each NaN in the MATLAB workspace is exportedto the database as NULL. Each NULL string in the database is readinto the MATLAB workspace as 'null'. Each 'null' string in theMATLAB workspace is exported to the database as a NULL string.

5-164

Page 349: Database Toolbox™ II

setdbprefs

• A MAT-file that specifies the JDBC source file has not been created.

• Visual Query Builder looks in the Windows system registry for datasources that do not appear in the ODBC.INI file.

• No temporary folder for registry settings has been specified.

• The default number of rows fetched from the Database server ata time for any query is 10,000.

Example 2 — Change a Preference

1 Run setdbprefs ('NullNumberRead').

setdbprefs ('NullNumberRead')NullNumberRead: 'NaN'

Each NULL number in the database is read into the MATLABworkspace as NaN.

2 Change the value of this preference to 0.

setdbprefs ('NullNumberRead', '0')

Each NULL number in the database is read into the MATLABworkspace as 0.

Example 3 — Change the DataReturnFormat Preference

1 Specify that database data be imported into MATLAB cell arrays.

setdbprefs ('DataReturnFormat','cellarray')

2 Import data into the MATLAB workspace.

conn = database('dbtoolboxdemo', '', '');curs=exec(conn, ...'select productnumber,productdescription from producttable');curs=fetch(curs,3);curs.Data

5-165

Page 350: Database Toolbox™ II

setdbprefs

ans =

[9] 'Victorian Doll'[8] 'Train Set'[7] 'Engine Kit'

Alternatively, you can use the native ODBC interface for an ODBCconnection. For more information, see database.

3 Change the data return format from cellarray to numeric.

setdbprefs ('DataReturnFormat','numeric')

4 Perform the same import operation as you ran in the cell arrayexample. Note the format of the returned data.

curs.Data

ans =

9 NaN8 NaN7 NaN

In the database, the values for productDescription are characterstrings, as seen in the previous example when DataReturnFormatwas set to cellarray. Therefore, the productDescription valuescannot be read when they are imported into the MATLAB workspaceusing the numeric format. Therefore, the MATLAB software treatsthem as NULL numbers and assigns them the current value for theNullNumberRead property of setdbprefs, NaN.

5 Change the data return format to structure.

setdbprefs ('DataReturnFormat','structure')

6 Perform the same import operation as you ran in the cell arrayexample.

5-166

Page 351: Database Toolbox™ II

setdbprefs

curs.Data

ans =

productnumber: [3x1 double]productdescription: {3x1 cell}

7 View the contents of the structure to see the data.

curs.Data.productdescription

ans =

'Victorian Doll''Train Set''Engine Kit'

curs.Data.productnumber

ans =

987

Example 4 — Change the Write Format for NULL Numbers

1 Specify NaN for the NullNumberWrite format.

setdbprefs('NullNumberWrite', 'NaN')

colnames = {'productNumber' ,'Quantity', 'Price'}

Numbers represented as NaN in the MATLAB workspace are exportedto databases as NULL.

5-167

Page 352: Database Toolbox™ II

setdbprefs

For example, the variable ex_data contains a NaN.

ex_data = {24, NaN, 30.00}

2 Insert ex_data into a database using fastinsert. The NaN data isexported into the database as NULL.

fastinsert (conn, 'inventoryTable', colnames, ex_data)

Example 5 — Specify Error Handling Settings

1 Specify the store format for the ErrorHandling preference.

setdbprefs ('ErrorHandling','store')

Errors generated from running database or exec are stored in theMessage field of the returned connection or cursor object.

2 Try to fetch data from a closed cursor.

conn=database('dbtoolboxdemo', '', '');

curs=exec(conn, 'select productdescription from producttable');

close(curs)

curs=fetch(curs,3);

curs =

Attributes: []

Data: 0

DatabaseObject: [1x1 database]

RowLimit: 0

SQLQuery: 'select productdescription from producttable'

Message: 'Invalid fetch cursor.'

Type: 'Database Cursor Object'

ResultSet: 0

Cursor: 0

Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

5-168

Page 353: Database Toolbox™ II

setdbprefs

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

The error generated by this operation appears in the Message field.

3 To specify the report format for the ErrorHandling preference, run:

setdbprefs ('ErrorHandling','report')

Errors generated by running database or exec appear immediatelyin the Command Window.

4 Try to fetch data from a closed cursor.

conn = database('dbtoolboxdemo', '', '');curs=exec(conn, 'select productdescription from producttable');close(curs)curs=fetch(curs,3);

Error using cursor/fetch>errorhandling (line 491)Invalid fetch cursor.

Error in cursor/fetch (line 460)errorhandling(outCursor.Message);

The error generated by this operation appears immediately in theCommand Window.

5 Specify the empty format for the ErrorHandling preference.

setdbprefs ('ErrorHandling','empty')

Errors generated while running database or exec are stored in theMessage field of the returned connection or cursor object. In addition,objects that cannot be created are returned as empty handles, [].

6 Try to fetch data from a closed cursor.

conn = database('dbtoolboxdemo', '', '');

curs=exec(conn, 'select productdescription from producttable');

5-169

Page 354: Database Toolbox™ II

setdbprefs

close(curs)

curs=fetch(curs,3);

curs =

Attributes: []

Data: 0

DatabaseObject: [1x1 database]

RowLimit: 0

SQLQuery: 'select productdescription from producttable'

Message: 'Invalid fetch cursor.'

Type: 'Database Cursor Object'

ResultSet: 0

Cursor: 0

Statement: [1x1 sun.jdbc.odbc.JdbcOdbcStatement]

Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]

The error appears in the cursor object Message field. Furthermore,the Attributes field contains empty handles because no attributescould be created.

Example 6 — Change Multiple Settings

Specify that NULL strings are read from the database into a MATLABmatrix of doubles as 'NaN':

setdbprefs({'NullStringRead';'DataReturnFormat'},...{'NaN';'numeric'})

See “Example 8 — Assign Values to a Structure” on page 5-171 for moreinformation on another way to change multiple settings.

Example 7 — Specify JDBC Data Sources for Use by VQB

Instruct VQB to connect to the database using the data sources specifiedin the file myjdbcdatsources.mat.

setdbprefs('JDBCDataSourceFile',...'D:/Work/myjdbcdatasources.mat')

5-170

Page 355: Database Toolbox™ II

setdbprefs

Example 8 — Assign Values to a Structure

1 Assign values for preferences to fields in the structure s.

s.DataReturnFormat = 'numeric';s.NullNumberRead = '0';s.TempDirForRegistryOutput = 'C:\Work's =

DataReturnFormat: 'numeric'NullNumberRead: '0'

TempDirForRegistryOutput: 'C:\Work'

2 Set preferences using the values in s:

setdbprefs(s)

3 Run setdbprefs to check your preferences settings:

setdbprefsDataReturnFormat: 'numeric'

ErrorHandling: 'store'NullNumberRead: '0'

NullNumberWrite: 'NaN'NullStringRead: 'null'

NullStringWrite: 'null'JDBCDataSourceFile: ''

UseRegistryForSources: 'yes'TempDirForRegistryOutput: 'C:\Work'

DefaultRowPreFetch: '10000'FetchInBatches: 'no'FetchBatchSize: '1000'

Example 9 — Return Values to a Structure

1 Assign values for all preferences to s by running:

s = setdbprefss =

5-171

Page 356: Database Toolbox™ II

setdbprefs

DataReturnFormat: 'cellarray'ErrorHandling: 'store'

NullNumberRead: 'NaN'NullNumberWrite: 'NaN'NullStringRead: 'null'

NullStringWrite: 'null'JDBCDataSourceFile: ''

UseRegistryForSources: 'yes'TempDirForRegistryOutput: 'C:\Work'

DefaultRowPreFetch: '10000'FetchInBatches: 'no'FetchBatchSize: '1000'

2 Use the MATLAB tab completion feature when obtaining the valuefor a preference. For example, enter:

s.U

3 Press the Tab key, and then Enter. MATLAB completes the fieldand displays the value.

s.UseRegistryForSources

ans =

yes

Example 10 — Save Preferences

You can save your preferences to a MAT-file to use them in futureMATLAB sessions. For example, say that you need to reuse preferencesthat you set for the Seasonal Smoothing project. Assign the preferencesto the variable SeasonalSmoothing and save them to a MAT-fileSeasonalSmoothingPrefs in your current folder:

SeasonalSmoothing = setdbprefs;save SeasonalSmoothingPrefs.mat SeasonalSmoothing

Later, load the data and restore the preferences:

5-172

Page 357: Database Toolbox™ II

setdbprefs

load SeasonalSmoothingPrefs.matsetdbprefs(SeasonalSmoothing);

See Also clear | fetch | getdatasources

RelatedExamples

• “Preference Settings for Large Data Import” on page 3-10• “Working with Preferences” on page 3-6

5-173

Page 358: Database Toolbox™ II

sql2native

Purpose Convert JDBC SQL grammar to SQL grammar native to system

Syntax n = sql2native(conn, 'sqlquery')

Description n = sql2native(conn, 'sqlquery') converts the SQL statementstring sqlquery from JDBC SQL grammar into the database system’snative SQL grammar for the connection conn. The native SQLstatement is assigned to n.

5-174

Page 359: Database Toolbox™ II

supports

Purpose Detect whether property is supported by database metadata object

Syntax a = supports(dbmeta)a = supports(dbmeta, 'property')a.property

Description a = supports(dbmeta) returns a structure that contains theproperties of dbmeta and its property values, 1 or 0. A value of 1indicates that the property is supported, and 0 indicates that theproperty is not supported.

a = supports(dbmeta, 'property') returns 1 or 0 for the propertyfield of dbmeta. A value of 1 indicates that the property is supported,and 0 indicates that the property is not supported.

a.property returns the value of property after you have created ausing the supports function.

Examples 1 Check if dbmeta supports group-by clauses.

a = supports(dbmeta, 'GroupBy')a =

1

2 View the value of all properties of dbmeta.

a = supports(dbmeta)

The returned result is a list of properties and their values.

3 See the value of the GroupBy property by running:

a.GroupBya =

1

See Also database | dmd | get | ping

5-175

Page 360: Database Toolbox™ II

tableprivileges

Purpose Return database table privileges

Syntax tp = tableprivileges(dbmeta, 'cata')tp = tableprivileges(dbmeta, 'cata', 'sch')tp = tableprivileges(dbmeta, 'cata', 'sch', 'tab')

Description tp = tableprivileges(dbmeta, 'cata') returns a list of tableprivileges for all tables in the catalog cata for the database whosedatabase metadata object is dbmeta resulting from a databaseconnection object.

tp = tableprivileges(dbmeta, 'cata', 'sch') returns a list oftable privileges for all tables in the schema sch, of the catalog cata,for the database whose database metadata object is dbmeta resultingfrom a database connection object.

tp = tableprivileges(dbmeta, 'cata', 'sch', 'tab') returns alist of privileges for the table tab, in the schema sch, of the catalogcata, for the database whose database metadata object is dbmetaresulting from a database connection object.

Examples Get table privileges for the builds table in the schema geck for thecatalog msdb, for the database metadata object dbmeta.

tp = tableprivileges(dbmeta,'msdb','geck', 'builds')tp =

'DELETE' 'INSERT' 'REFERENCES' ...'SELECT' 'UPDATE'

See Also dmd | get | tables

5-176

Page 361: Database Toolbox™ II

tables

Purpose Return database table names

Syntax t = tables(dbmeta, 'cata')t = tables(dbmeta, 'cata', 'sch')

Description t = tables(dbmeta, 'cata') returns a list of tables and table typesin the catalog cata for the database whose database metadata object isdbmeta resulting from a database connection object.

t = tables(dbmeta, 'cata', 'sch') returns a list of tables andtable types in the schema sch, of the catalog cata, for the databasewhose database metadata object is dbmeta resulting from a databaseconnection object.

Tip For command-line help on tables, use the overloaded method:

help dmd/tables

Examples Get the table names and types for the schema SCOTT in the catalogorcl, for the database metadata object dbmeta.

t = tables(dbmeta,'orcl', 'SCOTT')t =

'BONUS' 'TABLE''DEPT' 'TABLE''EMP' 'TABLE''SALGRADE' 'TABLE''TRIAL' 'TABLE'

See Also attr | bestrowid | dmd | get | indexinfo | tableprivileges

5-177

Page 362: Database Toolbox™ II

unregister

Purpose Unload database driver

Syntax unregister(d)

Description unregister(d) unloads the database driver object d, freeing up systemresources. If you do not unload a registered driver, it automaticallyunloads when you end your MATLAB session.

Examples unregister(d) unloads the database driver object d.

See Also register

5-178

Page 363: Database Toolbox™ II

update

Purpose Replace data in database table with MATLAB data

Syntax update(conn, 'tab', colnames, exdata, 'whereclause')

update(conn, 'tab', colnames, ...

{datA,datAA, ...; datB,datBB, ...; datn, datNN}, ...

{'where col1 = val1'; 'where col2 = val2'; ... 'where coln = valn'})

Description update(conn, 'tab', colnames, exdata, 'whereclause') exportsthe MATLAB variable exdata in its current format into the databasetable tab using the database connection conn. exdata can be a cellarray, numeric matrix, or structure. Existing records in the databasetable are replaced as specified by the SQL whereclause command.

Specify column names for tab as strings in the MATLAB cell arraycolnames. If exdata is a structure, field names in the structure mustmatch field names in colnames.

The status of the AutoCommit flag determines whether updateautomatically commits the data to the database. View the AutoCommitflag status for the connection using get and change it using set.Commit the data by running commit or a SQL commit statement viathe exec function. Roll back the data by running rollback or a SQLrollback statement via the exec function.

To add new rows instead of replacing existing data, use fastinsert.

update(conn, 'tab', colnames, {datA, datAA, ...; datB,datBB, ...; datn,datNN}, {'where col1 = val1'; 'where col2= val2'; ... 'where coln = valn'}) exports multiple records forn where clauses. The number of records in exdata must equal n.

Tips • The order of records in your database is not constant. Use values ofcolumn names to identify records.

• An error like the following may appear if your database table isopen in edit mode:

[Vendor][ODBC Product Driver] The database engine couldnot lock table 'TableName' because it is already in use

5-179

Page 364: Database Toolbox™ II

update

by another person or process.

In this case, close the table and repeat the update function.

• An error like the following may appear if you try to run an updateoperation that is identical to one that you just ran:

??? Error using ==> database.updateError:Commit/Rollback Problems

Examples Example 1 — Update an Existing Record

Using dbtoolboxdemo data source, update a record in theinventoryTable table using the database connection conn, whereproductNumber is 1, replacing the current value for Quantity with 2000.

1 Define a cell array containing the column name that you areupdating, Quantity.

colnames = {'Quantity'}

2 Define a cell array containing the new data, 2000.

exdata(1,1) = {2000}

3 Run the update.

update(conn, 'inventorytable', colnames, exdata, ...'where productNumber = 1')

5-180

Page 365: Database Toolbox™ II

update

Example 2 — Roll Back Data After Updating a Record

Using dbtoolboxdemo data source, update the column Price in theinventoryTable table for the record selected by whereclause, usingdata contained in the cell array exdata. The AutoCommit flag is off.The data is rolled back after the update operation is run.

1 Set the AutoCommit flag to off for database connection conn.

set(conn, 'AutoCommit', 'off')

2 Define a cell array containing the new data, 30.00.

exdata(1,1) = {30.00}

3 Define a where clause.

whereclause = 'where productNumber = 1'

4 Update the Price column.

update(conn, 'inventoryTable', {'Price'}, exdata, whereclause)

5 Because the data was not committed, you can roll it back.

rollback(conn)

The update is reversed; the data in the table is the same as it wasbefore you ran update.

Example 3 — Update Multiple Records with DifferentConstraints

Using dbtoolboxdemo data source, given the table inventoryTable,where column names are 'productNumber', 'Quantity', and 'Price':

A = 10000B = 5000

5-181

Page 366: Database Toolbox™ II

update

Assign productNumbers with values of 5 and8 to have a new Quantitywith the values of A and B:

update(conn, 'inventoryTable', {'Quantity'}, {A;B}, ...{'where productNumber = 5';'where productNumber = 8'})

See Also commit | database | fastinsert | rollback | set

5-182

Page 367: Database Toolbox™ II

versioncolumns

Purpose Automatically update table columns

Syntax vl = versioncolumns(dbmeta, 'cata')vl = versioncolumns(dbmeta, 'cata', 'sch')vl = versioncolumns(dbmeta, 'cata', 'sch', 'tab')

Description vl = versioncolumns(dbmeta, 'cata') returns a list of columns thatautomatically update when a row value updates in the catalog cata, inthe database whose database metadata object is dbmeta resulting froma database connection object.

vl = versioncolumns(dbmeta, 'cata', 'sch') returns a list ofall columns that automatically update when a row value updates inthe schema sch, in the catalog cata, for the database whose databasemetadata object is dbmeta resulting from a database connection object.

vl = versioncolumns(dbmeta, 'cata', 'sch', 'tab') returns alist of columns that automatically update when a row value updates inthe table tab, the schema sch, in the catalog cata, for the databasewhose database metadata object is dbmeta resulting from a databaseconnection object.

Examples Get a list of which columns automatically update when a row in thetable BONUS updates, in the schema SCOTT, in the catalog orcl, for thedatabase metadata object dbmeta.

vl = versioncolumns(dbmeta,'orcl','SCOTT','BONUS')vl =

{}

The results are an empty set, indicating that no columns in the databaseautomatically update when a row value updates.

See Also columns | dmd | get

5-183

Page 368: Database Toolbox™ II

width

Purpose Return field size of column in fetched data set

Syntax colsize = width(cursor, colnum)

Description colsize = width(cursor, colnum) returns the field size of thespecified column number colnum in the fetched data set curs.

Examples Get the width of the first column of the fetched data set, curs:

colsize = width(curs, 1)

colsize =

11

The field size of column one is 11 characters (bytes).

See Also attr | cols | columnnames | fetch | get

5-184

Page 369: Database Toolbox™ II

Index

IndexAadvanced query options in VQB 3-27All option in VQB 3-27arrays

data format 5-158data format in VQB 3-9

attr 5-2Attributes 5-96attributes of data

attr function 5-2AutoCommit

setting status 5-152status via get 5-95

Bbestrowid 5-4BINARY data types

retrieving with functions 4-25retrieving with VQB 3-51

BOOLEAN data typeretrieving 5-24 5-86VQB 3-54

CCatalog 5-95CatalogName 5-98cell arrays

data format 5-158for query results 4-4setting data format in VQB 3-6

chartingquery results 3-19

Charting dialog box 3-19clearwarnings 5-5close 5-6cols 5-8ColumnCount 5-98ColumnName 5-98

columnnames 5-9exporting example 4-15

columnprivileges 5-10columns 5-11

automatically updated 5-183cross reference 5-14exported keys 5-66foreign key information 5-104imported key information 5-104names, via attr 5-2names, via columnnames 5-9names, via columns 5-11number 5-8optimal set to identify row 5-4primary key information 5-128privileges 5-10width 5-184

ColumnTypeName 5-98columnWidth 5-2commit 5-12Condition in VQB 3-29confds

function reference 5-13Configure Data Source dialog box 5-13connection

clearing warnings for 5-5close function 5-6database, opening (establishing),

example 4-3information 5-126JDBC 5-95messages 5-95object 4-3properties, getting 5-94properties, setting 5-151read only 5-120status 5-126status, example 4-3time allowed for 5-122time allowed for, example 4-3

Index-1

Page 370: Database Toolbox™ II

Index

validity 5-115warnings 5-95

constructor functions 4-36crossreference 5-14currency 5-2Current clauses area in VQB

example 3-30cursor

attributes 5-96close function 5-6creating via fetch 5-17data element 5-96error messages 5-96objects

example 4-3opening 4-3properties 5-151properties, example 5-94resultset object 5-137

Cursor 5-96cursor.fetch 5-17

Ddata

attributes 5-2column names 5-9column numbers 5-8commit function 5-12committing 5-152displaying results in VQB 3-15exporting 5-68 5-109field names 5-9importing 5-17information about 4-5inserting into database 4-17replacing 4-12rolling back 5-138rolling back, via set 5-152rows function 5-139

unique occurrences of 3-27updating 5-179

Data 5-96Data Explorer

starting 5-49data format 5-158

Database Toolbox 3-9preferences for retrieval 5-158preferences in VQB 3-6

data sourcesdefining

JDBC 5-13JDBC

accessing 2-4modifying 2-5removing 2-6updating 2-5

ODBC connection 5-95ODBC, on system 5-103

data types 5-2BINARY, retrieving with functions 4-25BINARY, retrieving with VQB 3-51OTHER, retrieving with functions 4-25OTHER, retrieving with VQB 3-51supported 1-5

databaseconnecting to, example 4-3example 4-3JDBC connection 5-95metadata objects

creating 5-50properties 5-94properties supported 5-175

supported 1-2Database Toolbox requirements 1-2database.fetch 5-41DatabaseObject 5-96dbdemos 4-1demos 4-1

dbinfodemo 4-5

Index-2

Page 371: Database Toolbox™ II

Index

dbinsertdemo 4-8dbupdatedemo 4-12

dexplore 5-49displaying

query resultsas chart 3-19as report 3-21in MATLAB Report Generator

software 3-22relationally 3-15

Distinct option in VQB 3-27dmd 5-50

example 4-27driver 5-51

example 4-34object in get function 5-95

driver objectsfunctions, example 4-34properties 4-34

drivermanager 5-52drivermanager objects

example 4-34properties 5-151properties, via get 5-94

driversJDBC 1-3

troubleshooting 2-7JDBC compliance 5-117loading 5-136ODBC 1-3properties 5-94properties, drivermanager 5-52supported 1-3unloading 5-178validity 5-116

Drivers 5-98

Eediting clauses in VQB 3-31

empty field 4-26error handling

preferences 3-6error messages

cursor object 5-96database connection object 5-95

error notification, preferences 5-158examples

using functions 4-1exec

example 4-3with fetch 5-41

exportedkeys 5-66exporting data

inserting 5-68 5-109example 4-8multiple records 4-17

replacing 5-179replacing, example 4-12

Ffastinsert 5-68fetch

cursor 5-17database 5-41

Fetch 5-96fetchbatchsize

database.fetch 5-41fetchmulti 5-92fieldName 5-2fields

names 5-11size (width) 5-2

width 5-184foreign key information

crossreference 5-14exportedkeys 5-66importedkeys 5-104

format for data retrieved, preferences 5-158

Index-3

Page 372: Database Toolbox™ II

Index

freeing up resources 5-6functions

equivalent to VQB queries 3-59

Gget 4-35 5-94

properties 4-34getdatasources 5-103grouping statements 3-32

removing 3-36

HHandle 5-95HAVING Clauses dialog box 3-39Having in VQB 3-39HTML report of query results 3-21

MATLAB Report Generator software 3-22

Iimages

importing 4-25VQB 3-51

importedkeys 5-104importing data

bulk insertexample 4-18

data typesBINARY and OTHER using functions 4-25BINARY and OTHER using VQB 3-51

empty field 4-26using functions 5-17

example 4-3index for resultset column 5-125indexinfo 5-107insert 5-109inserting data into database 4-17Instance 5-95isconnection 5-115

isdriver 4-35 5-116isjdbc 5-117isNullable 5-98isnullcolumn 5-118isreadonly 5-120isReadOnly 5-98isurl 5-121

JJava® Database Connectivity. See JDBCJDBC

compliance 5-117connection object 5-95driver instance 5-95drivers

supported 1-3validity 5-116

MAT-file location preference 5-158SQL conversion to native grammar 5-174URL

via get 5-95join operation in VQB 3-47

Llogical data types

retrieving 5-24 5-86VQB 3-54

logintimeout 5-122example 4-3Macintosh platform support 5-122

LoginTimeoutDatabase connection object 5-95Drivermanager objects 5-98example 4-35

LogStream 5-98

MMajorVersion 5-97

Index-4

Page 373: Database Toolbox™ II

Index

MATLAB Report Generator softwaredisplay of query results 3-22

memory problemsfetchbatchsize solution 5-41RowLimit solution 5-17

Messageattr 5-2cursor object 5-96database connection object 5-95

metadata objectsdatabase 5-50

example 4-27resultset 5-140resultset functions 4-33

methods 4-36MinorVersion 5-97

Nnamecolumn 5-125nested SQL 3-42NULL values

detecting in imported record 5-118preferences for reading and writing 3-6reading from database 4-14representation in results 3-8setdbprefs 5-158writing to database 3-6

nullable 5-2numeric data format 5-158

VQB 3-6

Oobjects 4-36

creating 4-36properties, getting 5-94

ObjectType 5-95ODBC

data sources on system 5-103

drivers 1-3Open Database Connectivity. See ODBCOperator in VQB 3-31ORDER BY Clauses dialog box 3-37Order by option in VQB 3-36OTHER data types

retrieving with functions 4-25retrieving with VQB 3-51

Pparentheses, adding to statements 3-32ping 5-126

example 4-3platforms 1-2precision 5-2preferences

for Visual Query Builder 3-6primary key information 5-14primarykeys 5-128privileges

columns 5-10tables 5-176

procedurecolumns 5-130procedures 5-132properties

database metadata objects 5-175example 4-28

drivers 4-34getting 5-94setting 5-151

Qqueries

accessing subqueries in multiple tables 3-42accessing values in multiple tables 3-47displaying results

as chart 3-19as report 3-21

Index-5

Page 374: Database Toolbox™ II

Index

in MATLAB Report Generatorsoftware 3-22

relationally 3-15ordering results 3-36refining 3-29results 5-96

querybuilder 5-134querytimeout 5-135quotation marks

in table and column names 1-7

Rreadonly 5-2ReadOnly 5-95refining queries 3-29register 5-136Relation in VQB 3-29relational display of query results 3-15replacing data 4-12

update function 5-179reporting query results

MATLAB Report Generator software 3-22table 3-21

reserved wordsin table and column names 1-7

resultset 5-137clearing warnings for 5-5closing 5-6column name and index 5-125metadata objects 4-33

creating 5-140properties 5-94

properties 5-94ResultSet 5-96retrieving data

restrictions 1-7rollback 5-138RowLimit

get 5-96

set 5-153rows 5-139

uniquely identifying 5-4rsmd 5-140runstoredprocedure 5-149

Sscale 5-2set 5-151

example 4-35setdbprefs 5-158

example 4-14size 4-16Sort key number in VQB 3-37Sort order in VQB 3-37spaces

in table and column names 1-7speed

inserting data 5-68SQL

commands 1-4conversion to native grammar 5-174join in VQB 3-47statement

in exec 5-96in exec, example 4-3in VQB 3-31

time allowed for query 5-135where clause 5-179

sql2native 5-174SQLQuery 5-96Statement 5-96status of connection 5-126

example 4-3stored procedures

in catalog or schema 5-132information 5-130

string and numeric data format 5-158structure data format 5-158

Index-6

Page 375: Database Toolbox™ II

Index

VQB 3-6subqueries

in VQB 3-42Subquery dialog box 3-43supports 5-175

example 4-31system requirements 1-2

TTableName 5-98tableprivileges 5-176tables 5-177

example 4-33index information 5-107names 5-177privileges 5-176selecting multiple for VQB 3-48

timeallowed for connection 5-122allowed for SQL query 5-135

TimeOut 5-95TransactionIsolation 5-95Type 5-96typeName 5-2typeValue 5-2

Uungrouping statements 3-36

unique occurrences of data 3-27unregister 5-178update 5-179

example 4-12URL 5-95

validity 5-121user name 5-95

Vversioncolumns 5-183Visual Query Builder

advanced query options 3-27equivalent Database Toolbox functions 3-59getting started 3-2starting 5-134steps to export (insert) data 3-4steps to import (retrieve) data 3-2

VQB. See Visual Query Builder

WWarnings 5-95warnings, clearing 5-5where clause 5-179WHERE Clauses dialog box 3-29Where option in VQB 3-29width 5-184writable 5-95

Index-7