Database Toolbox™ User's Guide PDF
Database Toolbox™ User's Guide PDF
User’s Guide
R2014a
How to Contact MathWorks
www.mathworks.com Web
comp.soft-sys.matlab Newsgroup
www.mathworks.com/contact_TS.html Technical Support
508-647-7000 (Phone)
508-647-7001 (Fax)
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
May 1998 Online Only New for Version 1 for MATLAB® 5.2
July 1998 First Printing For Version 1
Online 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.1
June 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)
March 2014 Online only Revised for Version 5.1 (Release 2014a)
Contents
v
Choosing Between ODBC and JDBC Drivers . . . . . . . . . 2-10
Defining Database Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Deciding Between ODBC and JDBC Drivers . . . . . . . . . . . 2-10
vi Contents
Step 3. Add the JDBC driver to the MATLAB static Java
class path. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-52
Step 4. Set up the data source using Database Explorer. . . 2-53
Step 5. Connect using Database Explorer or the command
line. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-55
vii
Step 4. Connect using Database Explorer or the command
line. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-88
viii Contents
Oracle JDBC for Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-128
Step 1. Verify the driver installation. . . . . . . . . . . . . . . . . . 2-128
Step 2. Add the JDBC driver to the MATLAB static Java
class path. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-128
Step 3. Set up the data source using Database Explorer. . . 2-129
Step 4. Connect using Database Explorer or the command
line. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-131
ix
Step 2. Add the JDBC driver to the MATLAB static Java
class path. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-163
Step 3. Set up the data source using Database Explorer. . . 2-164
Step 4. Connect using Database Explorer or the command
line. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-166
x Contents
Sybase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-196
Other ODBC- or JDBC-Compliant Databases . . . . . . . . . . . 2-196
xi
Using the Native ODBC Database Connection . . . . . . . . 3-20
About the Native ODBC Interface . . . . . . . . . . . . . . . . . . . . 3-20
Native ODBC Interface Workflow . . . . . . . . . . . . . . . . . . . . 3-20
Native ODBC, JDBC/ODBC Bridge and JDBC Interface
Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-23
Compatibility and Limitations . . . . . . . . . . . . . . . . . . . . . . . 3-25
xii Contents
Using Having Clauses to Refine Group by Results . . . . . . . 4-48
Creating Subqueries for Values from Multiple Tables . . . . 4-51
Creating Queries That Include Results from Multiple
Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-56
Additional Advanced Query Options . . . . . . . . . . . . . . . . . . 4-59
xiii
Using Database Toolbox Functions
5
Getting Started with Database Toolbox Functions . . . . 5-2
xiv Contents
Using the fetch Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-42
About the fetch Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-42
fetch Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-42
Using fetch with a Cursor Object . . . . . . . . . . . . . . . . . . . . . 5-43
Database Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-44
xv
xvi Contents
1
Key Features
• Database Explorer app for working with databases interactively
• JDBC-compliant database connections
• ODBC-compliant database connections, with the option for fast access via a
native ODBC driver
• Functions for executing queries using SQL files and SQL statements
• Data import and export with multiple databases in a single session
• Large data set import via a single transaction or via multiple transactions
of segmented data
• Direct data import into numeric, cell, structure, and dataset arrays
1-2
Working with Databases
Connecting to Databases
Before you can use this toolbox to connect to a database, you must set up
the data sources. For details, see “Configuring a Driver and Data Source”
on page 2-13.
Platform Support
This toolbox runs on all platforms that the MATLAB software supports.
Note This toolbox does not support running MATLAB software sessions with
the -nojvm startup option enabled on UNIX® platforms. (UNIX is a registered
trademark of The Open Group in the United States and other countries.)
Database Support
This toolbox supports importing and exporting data from any ODBC- and/or
JDBC-compliant database management system, including:
1-3
1 Before You Begin
• IBM DB2®
• IBM® Informix
• Ingres®
• Microsoft Access™
• Microsoft Excel®
• Microsoft SQL Server
• MySQL
• Oracle
• PostgreSQL (Postgres)
• Sybase SQL Anywhere®
• Sybase SQL Server®
Driver Support
This toolbox requires a database driver. Typically, you install a driver when
you install a database. For instructions about how to install a database
driver, consult your database administrator.
1-4
Working with Databases
1-5
1 Before You Begin
• BOOLEAN
• CHAR
• DATE
• DECIMAL
• DOUBLE
• FLOAT
• INTEGER
• LONGCHAR
• NUMERIC
• REAL
• SMALLINT
• TIME
• TIMESTAMP
Note When importing TIMESTAMP data into MATLAB, you might get
an incorrect value near the daylight savings time change. Possible
workarounds are to convert TIMESTAMP data to strings in your SQL query,
and then convert them back to your desired type in MATLAB, or try using
a different driver for your database.
• TINYINT
1-6
Data Type Support
• VARCHAR
• NTEXT
You can import data of types not included in this list into the MATLAB
Workspace. However, you might need to manipulate such data before you
can process it in MATLAB.
Note Data types LONGCHAR and NTEXT are not supported for the native ODBC
interface.
1-7
1 Before You Begin
1-8
2
2-2
Working with a Database and MATLAB®
2 Choose whether you want to use Database Explorer or the command line
using the following flowchart.
3 Choose whether you want to use an ODBC or JDBC driver. For details, see
“Choosing Between ODBC and JDBC Drivers” on page 2-10.
5 Define your data source for ODBC-compliant drivers or add the full path of
the driver to the static Java class path for JDBC-compliant drivers. For
details, see “Configuring a Driver and Data Source” on page 2-13.
8 Select data from your database and import the data into a MATLAB
variable using Database Explorer or the command line exec and fetch
functions. For details, see “Selecting Data” on page 2-198.
9 Insert data into your database by exporting data from a MATLAB variable
using datainsert, fastinsert, and insert functions. For details, see
“Inserting Data Using the Command Line” on page 2-200.
2-3
2 Getting Started with Database Toolbox™
11 For a graphical representation of the steps and the decisions you must
make, see the following flowchart.
2-4
Working with a Database and MATLAB®
2-5
2 Getting Started with Database Toolbox™
Connection Options
In this section...
“Creating or Connecting to a Data Source” on page 2-6
“Defining Operating System Authentication” on page 2-6
“Connection Options” on page 2-6
“Working with Multiple Databases” on page 2-8
Connection Options
There are numerous ways to connect to your database using Database Toolbox.
The following explains each option. Use this table to choose your best option.
2-6
Connection Options
There are multiple options to connect to your database using the command
line. Use this table to choose your best option.
2-7
2 Getting Started with Database Toolbox™
2-8
Initial Setup Requirements
• For ODBC drivers, ensure 32-bit or 64-bit compatibility across your driver,
database, operating system, and MATLAB. For details, see “Configuring a
Driver and Data Source” on page 2-13.
• If you use Visual Query Builder (VQB) to explore the data in your database,
you need to migrate to the Database Explorer app. For details, see “Migrate
from Visual Query Builder (VQB) to Database Explorer” on page 4-73.
• Ensure you know the name of your database server or machine, the name
of your database, the port number, and your user name and password.
For ODBC drivers, once you create a data source, remember the data
source name. For JDBC drivers, ensure you know the file path of where
the JDBC driver is installed. For some JDBC drivers, you might need
the URL string and the driver Java class object. For some databases, you
might need to know more credentials. Contact your database administrator
for all required database credentials needed for establishing connection
to your database.
• Ensure you have access to your database and driver documentation.
• Check if your database uses Operating System Authentication. If you can
connect to your database from outside of MATLAB without providing a
user name and password, then your database uses Operating System
Authentication. Exceptions to this rule are databases set up without
any Operating System or database authentication requirements, such
as Microsoft Access or SQLite database files. Additional steps might be
required to set up connection to your database using Operating System
Authentication from MATLAB.
• Ensure you have write access to the path MATLAB displays after executing
prefdir on the command line.
2-9
2 Getting Started with Database Toolbox™
Database Toolbox has a Java library that connects directly to a pure JDBC
driver or uses the JDBC/ODBC bridge to connect to an ODBC driver. The
JDBC/ODBC bridge is automatically installed as part of the MATLAB
JVM™. Database Toolbox also has a C++ library that connects natively to
an ODBC driver.
2-10
Choosing Between ODBC and JDBC Drivers
The following figure illustrates how drivers interact with Database Toolbox.
Depending on your environment and what you want to accomplish, you need
to decide whether using an ODBC driver or a JDBC driver suits your needs
the best. Use the following to help you decide.
2-11
2 Getting Started with Database Toolbox™
Tip: On Windows systems that support both ODBC and JDBC drivers, pure
JDBC drivers and the native ODBC interface provide better connectivity and
performance than the JDBC/ODBC bridge. First, use the native ODBC or
JDBC drivers to connect to your database. Use the JDBC/ODBC bridge only
after trying to connect through native ODBC or JDBC drivers.
For a list of native ODBC supported functionality and a full comparison of the
JDBC/ODBC bridge to native ODBC, see “Using the Native ODBC Database
Connection” on page 3-20.
2-12
Configuring a Driver and Data Source
A Data Source Name (DSN) is the logical name that is used by Open Database
Connectivity (ODBC) to refer to the drive and other information that is
required to access data. This name is used to connect to an ODBC data
source, such as a Microsoft SQL Server database.
Database Platform
Windows Mac OS X Linux 64-bit
64-bit
Microsoft Access “Microsoft®
Access™ ODBC
for Windows” on
page 2-16
Microsoft SQL “Microsoft® SQL “Microsoft® SQL “Microsoft® SQL
Server Server® ODBC Server® JDBC Server® JDBC
for Windows” on for Mac OS X” on for Linux” on
page 2-25 page 2-107 page 2-114
“Microsoft® SQL
Server® JDBC
for Windows” on
page 2-35
2-13
2 Getting Started with Database Toolbox™
Database Platform
Windows Mac OS X Linux 64-bit
64-bit
Oracle “Oracle ODBC “Oracle JDBC for “Oracle JDBC for
for Windows” on Mac OS X” on Linux” on page
page 2-46 page 2-121 2-128
“Oracle JDBC
for Windows” on
page 2-51
MySQL “MySQL ODBC “MySQL JDBC “MySQL JDBC
for Windows” on for Mac OS X” on for Linux” on
page 2-59 page 2-135 page 2-142
“MySQL JDBC
for Windows” on
page 2-66
PostgreSQL “PostgreSQL “PostgreSQL “PostgreSQL
ODBC for JDBC for Mac JDBC for Linux”
Windows” on OS X” on page on page 2-156
page 2-72 2-149
“PostgreSQL
JDBC for
Windows” on
page 2-79
SQLite “SQLite JDBC “SQLite JDBC “SQLite JDBC
for Windows” on for Mac OS X” on for Linux” on
page 2-85 page 2-163 page 2-170
Sybase “Sybase ODBC “Sybase JDBC “Sybase JDBC
for Windows” on for Mac OS X” on for Linux” on
page 2-92 page 2-177 page 2-184
“Sybase JDBC
for Windows” on
page 2-100
Mac 32-bit and Linux 32-bit platforms are not supported. Microsoft Access is
not supported for Mac 64-bit and Linux 64-bit platforms.
2-14
Configuring a Driver and Data Source
For ODBC- or JDBC- compliant databases that are not listed in the table, see
“Other ODBC- or JDBC-Compliant Databases” on page 2-191.
2-15
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Check the 32-bit and 64-bit compatibility.” on page 2-16
“Step 2. Verify the driver installation.” on page 2-17
“Step 3. Set up the data source using Database Explorer.” on page 2-17
“Step 4. Connect using Database Explorer or the command line.” on page
2-21
2-16
Microsoft® Access™ ODBC for Windows®
When using a 32-bit version of Microsoft Office, you must also use a 32-bit
version of MATLAB to complete the following steps.
2-17
2 Getting Started with Database Toolbox™
3 Click the Database Explorer tab and then select New > ODBC.
The ODBC Data Source Administrator dialog box opens. Here, you can
define the ODBC data source.
2-18
Microsoft® Access™ ODBC for Windows®
4 Click the User DSN tab and then click Add. When setting up an ODBC
data source, you can use a User DSN or System DSN. A User DSN is
specific to the user on a machine. Any data sources a user defines under
User DSN are only seen by that specific user. Conversely, a System DSN
is not specific to the user on a machine. Any data sources a user defines
under System DSN on a machine can be seen by any user who logs into that
machine. Your ability to set up a User DSN or System DSN might depend
on the database and ODBC driver you are using. For details, contact your
database administrator or your database ODBC driver documentation.
5 A list of installed ODBC drivers appears in the Create New Data Source
dialog box. Select Microsoft Access Driver (*.mdb, *.accdb) and
click Finish.
6 The ODBC Microsoft Access Setup dialog box for your driver opens. Enter
dbtoolboxdemo as the data source name. Enter tutorial database as the
description. Click Select to open the Select Database dialog box.
2-19
2 Getting Started with Database Toolbox™
7 Specify the database you want to use. For the dbtoolboxdemo data source,
select tutorial.mdb. If your database is on a system to which your PC
is connected:
a Click Network. The Map Network Drive dialog box opens.
c Click Finish.
8 Click OK to close the Select Database dialog box. In the ODBC Microsoft
Access Setup dialog box, click OK. The ODBC Data Source Administrator
dialog box displays the dbtoolboxdemo and any additional data sources
that you added in the User DSN tab. Click OK to close the dialog box.
With the data source setup completed, you can connect to the Microsoft
Access database using Database Explorer or the command line with the
native ODBC or ODBC connection.
2-20
Microsoft® Access™ ODBC for Windows®
1 After setting up the data source, click Connect in the Database Explorer
tab. The Connect to a Data Source dialog box opens.
Database Explorer connects to the database and displays the tables list,
or database schema, on the left of the window.
2-21
2 Getting Started with Database Toolbox™
4 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the dbtoolboxdemo data source name on the database
tab. The Close button turns into a red circle ( ). Click it to close the
database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-right corner.
2-22
Microsoft® Access™ ODBC for Windows®
1 Connect to the database with the ODBC data source name. For example,
the following code assumes you are connecting to a data source named
dbtoolboxdemo with user name admin and password admin.
conn = database.ODBCConnection('dbtoolboxdemo','admin','admin');
close(conn);
1 Connect to the database with the ODBC data source name. For example,
the following code assumes you are connecting to a data source named
dbtoolboxdemo with user name admin and password admin.
conn = database('dbtoolboxdemo','admin','admin');
2-23
2 Getting Started with Database Toolbox™
close(conn);
2-24
Microsoft® SQL Server® ODBC for Windows®
In this section...
“Step 1. Check the 32-bit and 64-bit compatibility.” on page 2-25
“Step 2. Verify the driver installation.” on page 2-26
“Step 3. Set up the data source using Database Explorer.” on page 2-26
“Step 4. Connect using Database Explorer or the command line.” on page
2-31
2-25
2 Getting Started with Database Toolbox™
2-26
Microsoft® SQL Server® ODBC for Windows®
2 Click the Database Explorer tab and then select New > ODBC.
The ODBC Data Source Administrator dialog box opens. Here, you can
define the ODBC data source.
2-27
2 Getting Started with Database Toolbox™
3 Click the System DSN tab and then click Add. When setting up an ODBC
data source, you can use a User DSN or System DSN. A User DSN is
specific to the user on a machine. Any data sources a user defines under
User DSN are only seen by that specific user. Conversely, a System DSN
is not specific to the user on a machine. Any data sources a user defines
under System DSN on a machine can be seen by any user who logs into that
machine. Your ability to set up a User DSN or System DSN might depend
on the database and ODBC driver you are using. For details, contact your
database administrator or your database ODBC driver documentation.
4 A list of installed ODBC drivers appears in the Create New Data Source
dialog box. Select SQL Server Native Client 11.0 and click Finish.
5 The Create a New Data Source to SQL Server dialog box opens. Enter an
appropriate name for your data source. You use this name to establish a
connection to your database. For this example, enter MS SQL Server as
the data source name in the Name field. Enter Microsoft SQL Server
as the description in the Description field. Select the database server
for this data source to use in the Server field. Consult your database
administrator for the name of your database server. Click Next.
2-28
Microsoft® SQL Server® ODBC for Windows®
7 The Create a New Data Source to SQL Server dialog box opens. Select the
Change the default database to check box and enter the name of the
default database on the database server for connection. This example is
using the database toy_store. Then click Next.
9 The ODBC Microsoft SQL Server Setup dialog box opens. Test your
connection by clicking Test Data Source.
2-29
2 Getting Started with Database Toolbox™
10 The SQL Server ODBC Data Source Test dialog box opens. If the connection
establishes successfully, then the TESTS COMPLETED SUCCESSFULLY!
message appears. Click OK to close this dialog box. Click OK to close the
ODBC Microsoft SQL Server Setup dialog box.
2-30
Microsoft® SQL Server® ODBC for Windows®
11 The ODBC Data Source Administrator dialog box shows the new data
source under System Data Sources in the System DSN tab. Click OK to
close the ODBC Data Source Administrator dialog box.
With the data source setup completed, you can connect to the Microsoft
SQL Server database using Database Explorer or the command line with
the native ODBC connection.
1 After setting up the data source, click Connect in the Database Explorer
tab. The Connect to a Data Source dialog box opens.
2-31
2 Getting Started with Database Toolbox™
2-32
Microsoft® SQL Server® ODBC for Windows®
4 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the MS SQL Server ODBC data source name on the
database tab. The Close button turns into a red circle ( ). Click it to close
the database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-right corner.
2-33
2 Getting Started with Database Toolbox™
close(conn);
2-34
Microsoft® SQL Server® JDBC for Windows®
In this section...
“Step 1. Verify the driver installation.” on page 2-35
“Step 2. Verify the port number.” on page 2-35
“Step 3. Set up the Operating System authentication.” on page 2-38
“Step 4. Add the JDBC driver to the MATLAB static Java class path.”
on page 2-39
“Step 5. Set up the data source using Database Explorer.” on page 2-40
“Step 6. Connect using Database Explorer or the command line.” on page
2-42
2-35
2 Getting Started with Database Toolbox™
3 Check if TCP/IP is enabled. If so, skip the steps for enabling TCP/IP and
restarting the server.
5 To finish the process of enabling the TCP/IP protocol, restart the server.
Click SQL Server Services on the left side. Right-click SQL Server
(SQLEXPRESS) and click Restart.
2-36
Microsoft® SQL Server® JDBC for Windows®
7 In the IP Addresses tab, scroll to the bottom until you see IP All group.
The number next to the TCP Dynamic Ports field is the port number.
Use the port number you see in this dialog box in the JDBC connection
parameters for Database Explorer or the command line. In this example,
the port number is 53917. If this number is 0 or you want to configure your
Microsoft SQL Server database server to listen to a specific port, delete the
entry in the TCP Dynamic Ports field and enter another port number in
the TCP Port field.
2-37
2 Getting Started with Database Toolbox™
1 Ensure you have the latest Java driver library installed on your computer.
To install the latest library, see Driver Installation.
2-38
Microsoft® SQL Server® JDBC for Windows®
5 Open javalibrarypath.txt and insert the path to the Java library file
sqljdbc_auth.dll. The entry should include the full path to the library
file. The entry should not contain the library file name. For example,
C:\DB_Drivers\sqljdbc_4.0\enu\auth\x64.
<installation>\sqljdbc_<version>\<language>\auth\<arch>
6 Open MATLAB.
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the driver
file name, for example, C:\DB_Drivers\sqljdbc_4.0\enu\sqljdbc4.jar.
Save and close the javaclasspath.txt file.
5 Restart MATLAB.
2-39
2 Getting Started with Database Toolbox™
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-40
Microsoft® SQL Server® JDBC for Windows®
3 Select MICROSOFT SQL SERVER from the Vendor list. After selecting the
vendor, if you did not add the JDBC driver file path to the Java class path,
this dialog box displays this warning at the bottom. Address this warning
by following the steps as described in Step 4.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field.
2-41
2 Getting Started with Database Toolbox™
7 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
8 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Microsoft
SQL Server database using Database Explorer or the command line with
the JDBC connection.
2-42
Microsoft® SQL Server® JDBC for Windows®
3 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the MS SQL Server JDBC data source name on the
2-43
2 Getting Started with Database Toolbox™
database tab. The Close button turns into a red circle ( ). Click it to close
the database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-right corner.
2-44
Microsoft® SQL Server® JDBC for Windows®
'portnumber',123456);
close(conn);
2-45
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Check the 32-bit and 64-bit compatibility.” on page 2-46
“Step 2. Verify the driver installation.” on page 2-47
“Step 3. Set up the data source using the ODBC Data Source
Administrator.” on page 2-47
“Step 4. Connect using the native ODBC connection command line.” on
page 2-50
2-46
Oracle® ODBC for Windows®
2-47
2 Getting Started with Database Toolbox™
2 Click the System DSN tab and then click Add. When setting up an ODBC
data source, you can use a User DSN or System DSN. A User DSN is
specific to the user on a machine. Any data sources a user defines under
User DSN are only seen by that specific user. Conversely, a System DSN
is not specific to the user on a machine. Any data sources a user defines
under System DSN on a machine can be seen by any user who logs into that
machine. Your ability to set up a User DSN or System DSN might depend
on the database and ODBC driver you are using. For details, contact your
database administrator or your database ODBC driver documentation.
3 A list of installed ODBC drivers appears in the Create New Data Source
dialog box. Select the ODBC driver Oracle in OraClient11g_home1. Your
ODBC driver might have a different name. Click Finish.
2-48
Oracle® ODBC for Windows®
6 Click Test Connection to test the connection to your database. The Oracle
ODBC Driver Connect dialog box opens. If you are establishing the data
source with Windows authentication, the Testing Connection dialog box
opens instead.
7 Your database name and user name are automatically entered in the
Service Name and User Name fields. Enter your password in the
Password field. Click OK. The Testing Connection dialog box opens. If
your computer successfully connects to the database, Connection successful
appears. Click OK.
8 Click OK in the Oracle ODBC Driver Configuration dialog box. The ODBC
Data Source Administrator dialog box shows the ODBC data source ORA.
With the data source setup completed, you can connect to the Oracle
database using the command line with the native ODBC connection.
2-49
2 Getting Started with Database Toolbox™
conn = database.ODBCConnection('Oracle_Auth','','');
conn = database.ODBCConnection('Oracle','username','pwd');
close(conn);
2-50
Oracle® JDBC for Windows®
In this section...
“Step 1. Verify the driver installation.” on page 2-51
“Step 2. Set up the Operating System authentication.” on page 2-51
“Step 3. Add the JDBC driver to the MATLAB static Java class path.”
on page 2-52
“Step 4. Set up the data source using Database Explorer.” on page 2-53
“Step 5. Connect using Database Explorer or the command line.” on page
2-55
1 Ensure you have the latest Oracle OCI libraries installed on your computer.
To install the latest library, see Driver Installation.
2-51
2 Getting Started with Database Toolbox™
6 Add the Oracle OCI library full path to the Windows Path environment
variable.
7 Open MATLAB.
For details about Java libraries, see “Bringing Java Classes into MATLAB
Workspace”.
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, C:\DB_Drivers\ojdbc6.jar. Save and close
the javaclasspath.txt file.
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2-52
Oracle® JDBC for Windows®
2 Click the Database Explorer tab and then select New > JDBC.
2-53
2 Getting Started with Database Toolbox™
3 Select ORACLE from the Vendor list. After selecting the vendor, if you did
not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 3.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field.
2-54
Oracle® JDBC for Windows®
8 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
9 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Oracle
database using Database Explorer or the command line with the JDBC
connection.
2-55
2 Getting Started with Database Toolbox™
Or, to connect with Windows authentication, select the data source that
you set up. Leave the user name and password blank. Click Connect.
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the ORA JDBC data source name on the database tab.
2-56
Oracle® JDBC for Windows®
The Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-right corner.
dbname can be the service name or the Oracle system identifier (SID)
depending on your specific Oracle database setup. For details, see your
tnsnames.ora file, which is often in <ORACLE_HOME>\NETWORK\ADMIN
2-57
2 Getting Started with Database Toolbox™
where <ORACLE_HOME> is the folder where the database or the Oracle client
is installed.
conn = database('dbname','','',...
'Vendor','Oracle','DriverType','oci',...
'Server','sname','PortNumber',123456);
conn = database('dbname','username','pwd',...
'Vendor','Oracle','DriverType','thin',...
'Server','sname','PortNumber',123456);
If you have trouble using the database function to connect to your Oracle
database, try using the full entry in your tnsnames.ora file in the URL
string as one consecutive line. Leave the first argument blank. For
example, the following code assumes the value of the URL name-value pair
argument is set to the following tnsnames.ora file entry for an Oracle
database.
conn = database('','username','pwd',...
'Vendor','Oracle',...
'URL',['jdbc:oracle:thin:@(DESCRIPTION = ' ...
'(ADDRESS = (PROTOCOL = TCP)(HOST = sname)' ...
'(PORT = 123456)) (CONNECT_DATA = ' ...
'(SERVER = DEDICATED) (SERVICE_NAME = dbname) ) )']);
close(conn);
2-58
MySQL® ODBC for Windows®
In this section...
“Step 1. Check the 32-bit and 64-bit compatibility.” on page 2-59
“Step 2. Verify the driver installation.” on page 2-60
“Step 3. Set up the data source using Database Explorer.” on page 2-60
“Step 4. Connect using Database Explorer or the command line.” on page
2-63
2-59
2 Getting Started with Database Toolbox™
2 Click the Database Explorer tab and then select New > ODBC.
2-60
MySQL® ODBC for Windows®
The ODBC Data Source Administrator dialog box to define the ODBC data
source opens.
3 Click the System DSN tab and then click Add. When setting up an ODBC
data source, you can use a User DSN or System DSN. A User DSN is
specific to the user on a machine. Any data sources a user defines under
User DSN are only seen by that specific user. Conversely, a System DSN
is not specific to the user on a machine. Any data sources a user defines
2-61
2 Getting Started with Database Toolbox™
under System DSN on a machine can be seen by any user who logs into that
machine. Your ability to set up a User DSN or System DSN might depend
on the database and ODBC driver you are using. For details, contact your
database administrator or your database ODBC driver documentation.
4 A list of installed ODBC drivers appears in the Create New Data Source
dialog box. Select the ODBC driver MySQL ODBC 5.2a Driver. Your ODBC
driver might have a different name. Click Finish.
2-62
MySQL® ODBC for Windows®
6 Click Test to test the connection to your database. The Test Result dialog
box opens. If your computer successfully connects to the database, the
dialog box displays Connection successful.
The ODBC Data Source Administrator dialog box shows the ODBC data
source MySQL.
With the data source setup completed, you can connect to the MySQL
database using Database Explorer or the command line using the native
ODBC connection.
1 After setting up the data source, click Connect in the Database Explorer
tab. The Connect to a Data Source dialog box opens.
2 Connect to your database by selecting the data source name for the MySQL
database from the Data Sources list. Enter a user name and password.
Click Connect.
2-63
2 Getting Started with Database Toolbox™
3 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the MySQL ODBC data source name on the database
tab. The Close button turns into a red circle ( ). Click it to close the
database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-right corner.
2-64
MySQL® ODBC for Windows®
1 Connect to the database with the ODBC data source name. For example,
the following code assumes you are connecting to a data source named
MySQL with user name username and password pwd.
conn = database.ODBCConnection('MySQL','username','pwd');
close(conn);
2-65
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Verify the driver installation.” on page 2-66
“Step 2. Add JDBC driver to the MATLAB static Java class path.” on page
2-66
“Step 3. Set up the data source using Database Explorer.” on page 2-67
“Step 4. Connect using Database Explorer or the command line.” on page
2-69
2-66
MySQL® JDBC for Windows®
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-67
2 Getting Started with Database Toolbox™
3 Select MYSQL from the Vendor list. After selecting the vendor, if you did
not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field.
2-68
MySQL® JDBC for Windows®
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the MySQL
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the MySQL database from the Data Sources list.
Enter a user name and password. Click Connect.
2-69
2 Getting Started with Database Toolbox™
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the MySQL JDBC data source name on the database
tab. The Close button turns into a red circle ( ). Click it to close the
database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-right corner.
2-70
MySQL® JDBC for Windows®
conn = database('dbname','username','pwd',...
'Vendor','MySQL',...
'Server','sname');
close(conn);
2-71
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Check the 32-bit and 64-bit compatibility.” on page 2-72
“Step 2. Verify the driver installation.” on page 2-73
“Step 3. Set up the data source using Database Explorer.” on page 2-73
“Step 4. Connect using Database Explorer or the command line.” on page
2-76
2-72
PostgreSQL ODBC for Windows®
2-73
2 Getting Started with Database Toolbox™
2 Click the Database Explorer tab and then select New > ODBC.
The ODBC Data Source Administrator dialog box opens. Here, you can
define the ODBC data source
3 Click the System DSN tab and then click Add. When setting up an ODBC
data source, you can use a User DSN or System DSN. A User DSN is
specific to the user on a machine. Any data sources a user defines under
2-74
PostgreSQL ODBC for Windows®
User DSN are only seen by that specific user. Conversely, a System DSN
is not specific to the user on a machine. Any data sources a user defines
under System DSN on a machine can be seen by any user who logs into that
machine. Your ability to set up a User DSN or System DSN might depend
on the database and ODBC driver you are using. For details, contact your
database administrator or your database ODBC driver documentation.
4 A list of installed ODBC drivers appears in the Create New Data Source
dialog box. Select the ODBC driver PostgreSQL ANSI(x64). Your ODBC
driver might have a different name. Click Finish.
5 The PostgreSQL ANSI ODBC Driver (psqlODBC) Setup dialog box opens.
Enter an appropriate name for your data source in the Data Source field.
You use this name to establish a connection to your database. For this
example, enter PostgreSQL30 as the data source name. Enter a description
for this data source, such as PostgreSQL database, in the Description
field. Enter your database name in the Database field. Enter your
database server name in the Server field. Enter your port number in the
Port field. The default port number is 5432. Enter your user name in the
User Name field. Enter your password in the Password field. Leave all
settings in the Options section with default settings.
6 Click Test to test the connection to your database. The Connection Test
dialog box opens. If your computer successfully connects to the database,
the dialog box displays Connection successful.
2-75
2 Getting Started with Database Toolbox™
With the data source setup completed, you can connect to the PostgreSQL
database using Database Explorer or the native ODBC connection
command line.
1 After setting up the data source, click Connect in the Database Explorer
tab. The Connect to a Data Source dialog box opens.
2 Connect to your database by selecting the data source name for the
PostgreSQL database from the Data Sources list. Enter a user name and
password. Click Connect.
2-76
PostgreSQL ODBC for Windows®
3 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the PostgreSQL30 data source name on the database
tab. The Close button turns into a red circle ( ). Click it to close the
database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-right corner.
2-77
2 Getting Started with Database Toolbox™
1 Connect to the database with the ODBC data source name. For example,
the following code assumes you are connecting to a data source named
PostgreSQL with user name username and password pwd.
conn = database.ODBCConnection('PostgreSQL','username','pwd');
close(conn);
2-78
PostgreSQL JDBC for Windows®
In this section...
“Step 1. Verify the driver installation.” on page 2-79
“Step 2. Add the JDBC driver to the MATLAB static Java class path.”
on page 2-79
“Step 3. Set up the data source using Database Explorer.” on page 2-80
“Step 4. Connect using Database Explorer or the command line.” on page
2-82
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the driver
file name, for example, C:\DB_Drivers\postgresql-8.4-702.jdbc4.jar.
Save and close the javaclasspath.txt file.
5 Restart MATLAB.
2-79
2 Getting Started with Database Toolbox™
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-80
PostgreSQL JDBC for Windows®
3 Select POSTGRESQL from the Vendor list. After selecting the vendor, if you
did not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field.
2-81
2 Getting Started with Database Toolbox™
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the PostgreSQL
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the PostgreSQL database from the Data Sources
list. Enter a user name and password. Click Connect.
2-82
PostgreSQL JDBC for Windows®
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the Postgresql JDBC data source name on the
database tab. The Close button turns into a red circle ( ). Click it to close
the database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-right corner.
2-83
2 Getting Started with Database Toolbox™
conn = database('dbname','username','pwd',...
'Vendor','PostgreSQL',...
'Server','sname');
close(conn);
2-84
SQLite JDBC for Windows®
In this section...
“Step 1. Verify the driver installation.” on page 2-85
“Step 2. Add the JDBC driver to the MATLAB static Java class path.”
on page 2-85
“Step 3. Set up the data source using Database Explorer.” on page 2-86
“Step 4. Connect using Database Explorer or the command line.” on page
2-88
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, C:\DB_Drivers\sqlite-jdbc-3.7.2.jar.
Save and close the javaclasspath.txt file.
5 Restart MATLAB.
2-85
2 Getting Started with Database Toolbox™
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-86
SQLite JDBC for Windows®
4 Enter the SQLite driver Java class object in the Driver field. For this
example, use org.sqlite.JDBC. After entering the driver, if you did not
add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
5 Connect to the SQLite database by creating a URL string using the format
jdbc:subprotocol:subname. The jdbc part of this string stays constant
for any JDBC driver. subprotocol is a database type. In this case,
subprotocol is sqlite. The last part of the URL string is subname. For
SQLite, this contains the location of the database. For example, your string
2-87
2 Getting Started with Database Toolbox™
6 Enter your user name in the Username field and your password in the
Password field, or leave them blank if your database does not need them.
Click Test to test the connection. Database Explorer displays Connection
Successful! if your connection succeeded.
7 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
8 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the SQLite
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the SQLite database from the Data Sources list.
Enter a user name and password or leave them blank if your database does
not require them. Click Connect.
2-88
SQLite JDBC for Windows®
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the SQLite data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-right corner.
2-89
2 Getting Started with Database Toolbox™
2 Connect to the SQLite database by using the database function. Enter the
full path to your SQLite database dbpath for the first argument, or leave
this argument blank and include the full path in the URL string URL. Enter
your user name username and password pwd, or leave these blank if your
database does not require them. The fourth argument is the driver Java
class object. This code assumes the class object is org.sqlite.JDBC. The
last argument is the URL string URL.
conn = database(dbpath,username,pwd,'org.sqlite.JDBC','URL');
close(conn);
2-90
SQLite JDBC for Windows®
2-91
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Check the 32-bit and 64-bit compatibility.” on page 2-92
“Step 2. Verify the driver installation.” on page 2-93
“Step 3. Set up the data source using Database Explorer.” on page 2-93
“Step 4. Connect using Database Explorer or the command line.” on page
2-97
2-92
Sybase® ODBC for Windows®
2-93
2 Getting Started with Database Toolbox™
2 Click the Database Explorer tab and then select New > ODBC.
The ODBC Data Source Administrator dialog box to define the ODBC data
source opens.
3 Click the System DSN tab and then click Add. When setting up an ODBC
data source, you can use a User DSN or System DSN. A User DSN is
specific to the user on a machine. Any data sources a user defines under
2-94
Sybase® ODBC for Windows®
User DSN are only seen by that specific user. Conversely, a System DSN
is not specific to the user on a machine. Any data sources a user defines
under System DSN on a machine can be seen by any user who logs into that
machine. Your ability to set up a User DSN or System DSN might depend
on the database and ODBC driver you are using. For details, contact your
database administrator or your database ODBC driver documentation.
4 A list of installed ODBC drivers appears in the Create New Data Source
dialog box. Select the ODBC driver Adaptive Server Enterprise. Your
ODBC driver might have a different name. Click Finish.
2-95
2 Getting Started with Database Toolbox™
2-96
Sybase® ODBC for Windows®
With the data source setup completed, you can connect to the Sybase
database using Database Explorer or the command line using the native
ODBC connection.
1 After setting up the data source, click Connect in the Database Explorer
tab. The Connect to a Data Source dialog box opens.
2 Connect to your database by selecting the data source name for the Sybase
database from the Data Sources list. Enter a user name and password.
Click Connect.
2-97
2 Getting Started with Database Toolbox™
3 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the Sybase data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-right corner.
2-98
Sybase® ODBC for Windows®
1 Connect to your database with the ODBC data source name. For example,
the following code assumes you are connecting to a data source named
Sybase with user name username and password pwd.
conn = database.ODBCConnection('Sybase','username','pwd');
close(conn);
2-99
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Verify the driver installation.” on page 2-100
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-100
“Step 3. Set up the data source using Database Explorer.” on page 2-101
“Step 4. Connect using Database Explorer or the command line.” on page
2-103
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, C:\DB_Drivers\jconn4.jar. Save and close
the javaclasspath.txt file.
5 Restart MATLAB.
2-100
Sybase® JDBC for Windows®
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-101
2 Getting Started with Database Toolbox™
4 Enter the Sybase driver Java class object in the Driver field. For this
example, use com.sybase.jdbc4.jdbc.SybDriver. After entering the
driver, if you did not add the JDBC driver file path to the Java class path,
this dialog box displays this warning at the bottom. Address this warning
by following the steps as described in Step 2.
2-102
Sybase® JDBC for Windows®
port number, and the database name. For example, your string is
jdbc:sybase:Tds:ServerName:PortNumber/dbname, where ServerName
is your server name, PortNumber is your port number, and dbname is your
database name. Enter your full string into the URL field.
6 Enter your user name in the Username field and your password in the
Password field. Click Test to test the connection. Database Explorer
displays Connection Successful! if your connection succeeded.
7 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
8 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Sybase
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the Sybase database from the Data Sources list.
Enter a user name and password. Click Connect.
2-103
2 Getting Started with Database Toolbox™
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the Sybase JDBC data source name on the database
tab. The Close button turns into a red circle ( ). Click it to close the
2-104
Sybase® JDBC for Windows®
2 Connect to the Sybase database using the database function. For example,
the following code assumes you are connecting to a database named
dbname with user name username and password pwd. The fourth argument
is the driver Java class object. This code assumes the class object is
2-105
2 Getting Started with Database Toolbox™
conn = database('dbname','username','pwd',...
'com.sybase.jdbc4.jdbc.SybDriver','URL');
close(conn);
2-106
Microsoft® SQL Server® JDBC for Mac OS X
In this section...
“Step 1. Verify the driver installation.” on page 2-107
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-107
“Step 3. Set up the data source using Database Explorer.” on page 2-108
“Step 4. Connect using Database Explorer or the command line.” on page
2-110
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, /home/user/DB_Drivers/sqljdbc4.jar.
Save and close the javaclasspath.txt file.
2-107
2 Getting Started with Database Toolbox™
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-108
Microsoft® SQL Server® JDBC for Mac OS X
3 Select MICROSOFT SQL SERVER from the Vendor list. After selecting the
vendor, if you did not add the JDBC driver file path to the Java class path,
this dialog box displays this warning at the bottom. Address this warning
by following the steps as described in Step 2.
4 Enter the database server name in the Server Name, port number in
the Port Number field, user name in the Username field, password in
2-109
2 Getting Started with Database Toolbox™
the Password field, and database name in the Database field. Set the
Authentication Type to Server.
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Microsoft
SQL Server database using Database Explorer or the command line with
the JDBC connection.
1 After setting up the data source, select the data source that you set up from
the Data Sources list. Enter a user name and password. Click Connect.
2-110
Microsoft® SQL Server® JDBC for Mac OS X
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the MS_SQL_Server data source name on the database
tab. The Close button turns into a red circle ( ). Click it to close the
database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-left corner.
2-111
2 Getting Started with Database Toolbox™
close(conn);
2-112
Microsoft® SQL Server® JDBC for Mac OS X
2-113
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Verify the driver installation.” on page 2-114
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-114
“Step 3. Set up the data source using Database Explorer.” on page 2-115
“Step 4. Connect using Database Explorer or the command line.” on page
2-117
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, /home/user/DB_Drivers/sqljdbc4.jar.
Save and close the javaclasspath.txt file.
2-114
Microsoft® SQL Server® JDBC for Linux®
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-115
2 Getting Started with Database Toolbox™
3 Select MICROSOFT SQL SERVER from the Vendor list. After selecting the
vendor, if you did not add the JDBC driver file path to the Java class path,
this dialog box displays this warning at the bottom. Address this warning
by following the steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field. Set the
Authentication Type to Server.
2-116
Microsoft® SQL Server® JDBC for Linux®
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Microsoft
SQL Server database using Database Explorer or the command line with
the JDBC connection.
1 After setting up the data source, select the data source that you set up from
the Data Sources list. Enter a user name and password. Click Connect.
2-117
2 Getting Started with Database Toolbox™
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the MS_SQL_Server data source name on the database
tab. The Close button turns into a red circle ( ). Click it to close the
database connection. If you want to close Database Explorer and all
database connections, click the Close button ( ) in the top-right corner.
2-118
Microsoft® SQL Server® JDBC for Linux®
close(conn);
2-119
2 Getting Started with Database Toolbox™
2-120
Oracle® JDBC for Mac OS X
In this section...
“Step 1. Verify the driver installation.” on page 2-121
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-121
“Step 3. Set up the data source using Database Explorer.” on page 2-122
“Step 4. Connect using Database Explorer or the command line.” on page
2-124
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, /home/user/DB_Drivers/ojdbc6.jar. Save
and close the javaclasspath.txt file.
2-121
2 Getting Started with Database Toolbox™
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-122
Oracle® JDBC for Mac OS X
3 Select ORACLE from the Vendor list. After selecting the vendor, if you did
not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number
in the Port Number field, user name in the Username field, password
in the Password field, and database name in the Database field. Select
2-123
2 Getting Started with Database Toolbox™
Driver Type of thin or oci. Use thin as the default driver. Use oci if
you installed an OCI driver.
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Oracle
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, select the data source that you set up from
the Data Sources list. Enter a user name and password. Click Connect.
2-124
Oracle® JDBC for Mac OS X
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the ORA data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-left corner.
2-125
2 Getting Started with Database Toolbox™
dbname can be the service name or the Oracle system identifier (SID)
depending on your specific Oracle database setup. For details, see your
tnsnames.ora file, which is often in <ORACLE_HOME>\NETWORK\ADMIN
where <ORACLE_HOME> is the folder where the database or the Oracle client
is installed.
conn = database('dbname','username','pwd',...
'Vendor','Oracle','DriverType','thin',...
'Server','sname','PortNumber',123456);
2-126
Oracle® JDBC for Mac OS X
Or, if you have trouble using the database function to connect to your
Oracle database, try using the full entry in your tnsnames.ora file in the
URL string as one consecutive line. Leave the first argument blank. For
example, the following code assumes the value of the URL name-value pair
argument is set to the following tnsnames.ora file entry for an Oracle
database.
conn = database('','username','pwd',...
'Vendor','Oracle',...
'URL',['jdbc:oracle:thin:@(DESCRIPTION = ' ...
'(ADDRESS = (PROTOCOL = TCP)(HOST = sname)' ...
'(PORT = 123456)) (CONNECT_DATA = ' ...
'(SERVER = DEDICATED) (SERVICE_NAME = dbname) ) )']);
close(conn);
2-127
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Verify the driver installation.” on page 2-128
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-128
“Step 3. Set up the data source using Database Explorer.” on page 2-129
“Step 4. Connect using Database Explorer or the command line.” on page
2-131
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, /home/user/DB_Drivers/ojdbc6.jar. Save
and close the javaclasspath.txt file.
2-128
Oracle® JDBC for Linux®
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-129
2 Getting Started with Database Toolbox™
3 Select ORACLE from the Vendor list. After selecting the vendor, if you did
not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number
in the Port Number field, user name in the Username field, password
in the Password field, and database name in the Database field. Select
Driver Type of thin or oci. Use thin as the default driver. Use oci if
you installed an OCI driver.
2-130
Oracle® JDBC for Linux®
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Oracle
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, select the data source that you set up from
the Data Sources list. Enter a user name and password. Click Connect.
2-131
2 Getting Started with Database Toolbox™
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the ORA data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-right corner.
2-132
Oracle® JDBC for Linux®
dbname can be the service name or the Oracle system identifier (SID)
depending on your specific Oracle database setup. For details, see your
tnsnames.ora file, which is often in <ORACLE_HOME>\NETWORK\ADMIN
where <ORACLE_HOME> is the folder where the database or the Oracle client
is installed.
conn = database('dbname','username','pwd',...
'Vendor','Oracle','DriverType','thin',...
'Server','sname','PortNumber',123456);
2-133
2 Getting Started with Database Toolbox™
Or, if you have trouble using the database function to connect to your
Oracle database, try using the full entry in your tnsnames.ora file in the
URL string as one consecutive line. Leave the first argument blank. For
example, the following code assumes the value of the URL name-value pair
argument is set to the following tnsnames.ora file entry for an Oracle
database.
conn = database('','username','pwd',...
'Vendor','Oracle',...
'URL',['jdbc:oracle:thin:@(DESCRIPTION = ' ...
'(ADDRESS = (PROTOCOL = TCP)(HOST = sname)' ...
'(PORT = 123456)) (CONNECT_DATA = ' ...
'(SERVER = DEDICATED) (SERVICE_NAME = dbname) ) )']);
close(conn);
2-134
MySQL® JDBC for Mac OS X
In this section...
“Step 1. Verify the driver installation.” on page 2-135
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-135
“Step 3. Set up the data source using Database Explorer.” on page 2-136
“Step 4. Connect using Database Explorer or the command line.” on page
2-138
2-135
2 Getting Started with Database Toolbox™
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-136
MySQL® JDBC for Mac OS X
3 Select MYSQL from the Vendor list. After selecting the vendor, if you did
not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field.
2-137
2 Getting Started with Database Toolbox™
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the MySQL
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the MySQL database from the Data Sources list.
Enter a user name and password. Click Connect.
2-138
MySQL® JDBC for Mac OS X
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the MySQL data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-left corner.
2-139
2 Getting Started with Database Toolbox™
conn = database('dbname','username','pwd',...
'Vendor','MySQL',...
'Server','sname');
close(conn);
2-140
MySQL® JDBC for Mac OS X
2-141
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Verify the driver installation.” on page 2-142
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-142
“Step 3. Set up the data source using Database Explorer.” on page 2-143
“Step 4. Connect using Database Explorer or the command line.” on page
2-145
2-142
MySQL® JDBC for Linux®
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-143
2 Getting Started with Database Toolbox™
3 Select MYSQL from the Vendor list. After selecting the vendor, if you did
not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field.
2-144
MySQL® JDBC for Linux®
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the MySQL
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the MySQL database from the Data Sources list.
Enter a user name and password. Click Connect.
2-145
2 Getting Started with Database Toolbox™
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the MySQL data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-right corner.
2-146
MySQL® JDBC for Linux®
conn = database('dbname','username','pwd',...
'Vendor','MySQL',...
'Server','sname');
close(conn);
2-147
2 Getting Started with Database Toolbox™
2-148
PostgreSQL JDBC for Mac OS X
In this section...
“Step 1. Verify the driver installation.” on page 2-149
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-149
“Step 3. Set up the data source using Database Explorer.” on page 2-150
“Step 4. Connect using Database Explorer or the command line.” on page
2-152
2-149
2 Getting Started with Database Toolbox™
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-150
PostgreSQL JDBC for Mac OS X
3 Select POSTGRESQL from the Vendor list. After selecting the vendor, if you
did not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field.
2-151
2 Getting Started with Database Toolbox™
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the PostgreSQL
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the PostgreSQL database from the Data Sources
list. Enter a user name and password. Click Connect.
2-152
PostgreSQL JDBC for Mac OS X
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the PostgreSQL data source name on the database tab.
The Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-left corner.
2-153
2 Getting Started with Database Toolbox™
conn = database('dbname','username','pwd',...
'Vendor','PostgreSQL',...
'Server','sname');
close(conn);
2-154
PostgreSQL JDBC for Mac OS X
2-155
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Verify the driver installation.” on page 2-156
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-156
“Step 3. Set up the data source using Database Explorer.” on page 2-157
“Step 4. Connect using Database Explorer or the command line.” on page
2-159
2-156
PostgreSQL JDBC for Linux®
5 Restart MATLAB.
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-157
2 Getting Started with Database Toolbox™
3 Select POSTGRESQL from the Vendor list. After selecting the vendor, if you
did not add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
4 Enter the database server name in the Server Name field, port number in
the Port Number field, user name in the Username field, password in
the Password field, and database name in the Database field.
2-158
PostgreSQL JDBC for Linux®
6 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
7 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the PostgreSQL
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the PostgreSQL database from the Data Sources
list. Enter a user name and password. Click Connect.
2-159
2 Getting Started with Database Toolbox™
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the PostgreSQL data source name on the database tab.
The Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-right corner.
2-160
PostgreSQL JDBC for Linux®
conn = database('dbname','username','pwd',...
'Vendor','PostgreSQL',...
'Server','sname');
close(conn);
2-161
2 Getting Started with Database Toolbox™
2-162
SQLite JDBC for Mac OS X
In this section...
“Step 1. Verify the driver installation.” on page 2-163
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-163
“Step 3. Set up the data source using Database Explorer.” on page 2-164
“Step 4. Connect using Database Explorer or the command line.” on page
2-166
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the driver
file name, for example, /home/user/DB_Drivers/sqlite-jdbc-3.7.2.jar.
Save and close the javaclasspath.txt file.
5 Restart MATLAB.
2-163
2 Getting Started with Database Toolbox™
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-164
SQLite JDBC for Mac OS X
4 Enter the SQLite driver Java class object in the Driver field. For this
example, use org.sqlite.JDBC. After entering the driver, if you did not
add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
5 Connect to the SQLite database by creating a URL string using the format
jdbc:subprotocol:subname. The jdbc part of this string stays constant
for any JDBC driver. subprotocol is a database type. In this case,
subprotocol is sqlite. The last part of the URL string is subname. For
2-165
2 Getting Started with Database Toolbox™
SQLite, this contains the location of the database. For example, your string
is jdbc:sqlite:dbpath, where dbpath is the full path to your SQLite
database on your computer. Enter your string into the URL field.
6 Enter your user name in the Username field and your password in the
Password field, or leave them blank if your database does not need them.
8 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
9 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the SQLite
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the SQLite database from the Data Sources list.
Enter a user name and password or leave them blank if your database does
not require them. Click Connect.
2-166
SQLite JDBC for Mac OS X
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the Sqlite data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-left corner.
2-167
2 Getting Started with Database Toolbox™
2 Connect to the SQLite database by using the database function. Enter the
full path to your SQLite database dbpath for the first argument, or leave
this argument blank and include the full path in the URL string URL. Enter
your user name username and your password pwd, or leave these blank if
your database does not require them. The fourth argument is the driver
Java class object. This code assumes the class object is org.sqlite.JDBC.
The last argument is the URL string URL.
conn = database(dbpath,username,pwd,'org.sqlite.JDBC','URL');
2-168
SQLite JDBC for Mac OS X
close(conn);
2-169
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Verify the driver installation.” on page 2-170
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-170
“Step 3. Set up the data source using Database Explorer.” on page 2-171
“Step 4. Connect using Database Explorer or the command line.” on page
2-173
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the driver
file name, for example, /home/user/DB_Drivers/sqlite-jdbc-3.7.2.jar.
Save and close the javaclasspath.txt file.
5 Restart MATLAB.
2-170
SQLite JDBC for Linux®
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-171
2 Getting Started with Database Toolbox™
4 Enter the SQLite driver Java class object in the Driver field. For this
example, use org.sqlite.JDBC. After entering the driver, if you did not
add the JDBC driver file path to the Java class path, this dialog box
displays this warning at the bottom. Address this warning by following the
steps as described in Step 2.
5 Connect to the SQLite database by creating a URL string using the format
jdbc:subprotocol:subname. The jdbc part of this string stays constant
for any JDBC driver. subprotocol is a database type. In this case,
subprotocol is sqlite. The last part of the URL string is subname. For
SQLite, this contains the location of the database. For example, your string
2-172
SQLite JDBC for Linux®
6 Enter your user name in the Username field and your password in the
Password field, or leave them blank if your database does not need them.
8 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
9 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the SQLite
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the SQLite database from the Data Sources list.
Enter a user name and password or leave them blank if your database does
not require them. Click Connect.
2-173
2 Getting Started with Database Toolbox™
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the Sqlite data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-right corner.
2-174
SQLite JDBC for Linux®
2 Connect to the SQLite database by using the database function. Enter the
full path to your SQLite database dbpath for the first argument, or leave
this argument blank and include the full path in the URL string URL. Enter
your user name username and your password pwd, or leave these blank if
your database does not require them. The fourth argument is the driver
Java class object. This code assumes the class object is org.sqlite.JDBC.
The last argument is the URL string URL.
conn = database(dbpath,username,pwd,'org.sqlite.JDBC','URL');
close(conn);
2-175
2 Getting Started with Database Toolbox™
2-176
Sybase® JDBC for Mac OS X
In this section...
“Step 1. Verify the driver installation.” on page 2-177
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-177
“Step 3. Set up the data source using Database Explorer.” on page 2-178
“Step 4. Connect using Database Explorer or the command line.” on page
2-180
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, /home/user/DB_Drivers/jconn4.jar. Save
and close the javaclasspath.txt file.
5 Restart MATLAB.
2-177
2 Getting Started with Database Toolbox™
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-178
Sybase® JDBC for Mac OS X
4 Enter the Sybase driver Java class object in the Driver field. For this
example, use com.sybase.jdbc4.jdbc.SybDriver. After entering the
driver, if you did not add the JDBC driver file path to the Java class path,
this dialog box displays this warning at the bottom. Address this warning
by following the steps as described in Step 2.
2-179
2 Getting Started with Database Toolbox™
string is subname. For Sybase, this contains the server name, the
port number, and the database name. For example, your string is
jdbc:sybase:Tds:ServerName:PortNumber/dbname, where ServerName
is your server name, PortNumber is your port number, and dbname is your
database name. Enter your full string into the URL field.
6 Enter your user name in the Username field and your password in the
Password field.
8 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
9 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Sybase
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the Sybase database from the Data Sources list.
Enter a user name and password. Click Connect.
2-180
Sybase® JDBC for Mac OS X
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the Sybase data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-left corner.
2-181
2 Getting Started with Database Toolbox™
2 Connect to the Sybase database using the database function. For example,
the following code assumes you are connecting to a database named
dbname with user name username and password pwd. The fourth argument
is the driver Java class object. This code assumes the class object is
com.sybase.jdbc4.jdbc.SybDriver. The last argument is the URL string
URL.
2-182
Sybase® JDBC for Mac OS X
conn = database('dbname','username','pwd',...
'com.sybase.jdbc4.jdbc.SybDriver','URL');
close(conn);
2-183
2 Getting Started with Database Toolbox™
In this section...
“Step 1. Verify the driver installation.” on page 2-184
“Step 2. Add the JDBC driver to the MATLAB static Java class path.” on
page 2-184
“Step 3. Set up the data source using Database Explorer.” on page 2-185
“Step 4. Connect using Database Explorer or the command line.” on page
2-187
4 Open javaclasspath.txt and insert the path to the database driver JAR
file. The entry should include the full path to the driver including the
driver file name, for example, /home/user/DB_Drivers/jconn4.jar. Save
and close the javaclasspath.txt file.
5 Restart MATLAB.
2-184
Sybase® JDBC for Linux®
Alternatively, you can use javaaddpath to add your JDBC driver to the
dynamic Java class path. For details about static and dynamic class paths,
see “Bringing Java Classes into MATLAB Workspace”.
2 Click the Database Explorer tab and then select New > JDBC.
2-185
2 Getting Started with Database Toolbox™
4 Enter the Sybase driver Java class object in the Driver field. For this
example, use com.sybase.jdbc4.jdbc.SybDriver. After entering the
driver, if you did not add the JDBC driver file path to the Java class path,
this dialog box displays this warning at the bottom. Address this warning
by following the steps as described in Step 2.
2-186
Sybase® JDBC for Linux®
6 Enter your user name in the Username field and your password in the
Password field.
8 Enter a data source name in the Data Source Name field in the Create a
New JDBC data source dialog box. Use a new data source name that does
not appear in the existing list of data source names. Click Save. The new
JDBC data source appears in the list of data sources in the Connect to
a Data Source dialog box.
9 If this is the first time you are creating a data source using Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions. This
MAT-file name is stored in setdbprefs('JDBCDataSourceFile') and is
valid for all MATLAB sessions.
Navigate to the folder where you want to put the MAT-file, specify a name
for it that includes a .mat extension, and click Save.
With the data source setup completed, you can connect to the Sybase
database using Database Explorer or the command line with the JDBC
connection.
1 After setting up the data source, connect to your database by selecting the
data source name for the Sybase database from the Data Sources list.
Enter a user name and password. Click Connect.
2-187
2 Getting Started with Database Toolbox™
2 Close the connection using Database Explorer by hovering over the Close
button ( ) next to the Sybase data source name on the database tab. The
Close button turns into a red circle ( ). Click it to close the database
connection. If you want to close Database Explorer and all database
connections, click the Close button ( ) in the top-right corner.
2-188
Sybase® JDBC for Linux®
2 Connect to the Sybase database using the database function. For example,
the following code assumes you are connecting to a database named
dbname with user name username and password pwd. The fourth argument
is the driver Java class object. This code assumes the class object is
com.sybase.jdbc4.jdbc.SybDriver. The last argument is the URL string
URL.
2-189
2 Getting Started with Database Toolbox™
conn = database('dbname','username','pwd',...
'com.sybase.jdbc4.jdbc.SybDriver','URL');
close(conn);
2-190
Other ODBC- or JDBC-Compliant Databases
In this section...
“ODBC-Compliant Databases” on page 2-191
“JDBC-Compliant Databases” on page 2-192
ODBC-Compliant Databases
This tutorial shows how to configure your driver and connect to your
ODBC-compliant database with MATLAB. Database Toolbox can connect to
any ODBC-compliant database that is relational and that uses ANSI SQL.
For example, if your database is Microsoft Excel or IBM DB2, here are some
basic steps to follow.
2 Create a data source that uses the installed driver using the Microsoft
Data Source ODBC Administrator. For details about the Microsoft Data
Source ODBC Administrator, see Driver Installation.
3 Use Database Explorer to test your connection. For details, see “Configure
ODBC Data Sources” on page 4-75.
5 Alternatively, you can connect to your database using the command line
function database.
2-191
2 Getting Started with Database Toolbox™
JDBC-Compliant Databases
This tutorial shows how to configure your driver and connect to your
JDBC-compliant database with MATLAB. Database Toolbox can connect to
any JDBC-compliant database that is relational and that uses ANSI SQL.
For example, if your database is Apache Derby or Microsoft Windows Azure,
here are some basic steps to follow. The details of the steps below can vary
depending on your database and database version. For details about your
database, contact your database administrator or refer to your database
documentation. The driver and URL fields (in Database Explorer Create a
New JDBC data source dialog box and in the database command) can vary
depending on the type and version of the JDBC driver and the database you
are working with. For details about the driver and URL, see the JDBC driver
documentation for your database.
2 Add the JDBC driver path to the static Java class path, or alternatively to
the dynamic Java class path. For details about static and dynamic class
paths, see “Bringing Java Classes into MATLAB Workspace”.
5 Use Database Explorer to test your connection. For details, see “Configure
JDBC Data Sources” on page 4-80.
2-192
Other ODBC- or JDBC-Compliant Databases
7 Alternatively, you can connect to your database using the command line
function database.
2-193
2 Getting Started with Database Toolbox™
Connecting to a Database
To connect to your database, your ODBC or JDBC driver must be installed and
your data source must be defined. For details about driver installation and
data source setup, see “Configuring a Driver and Data Source” on page 2-13.
In this section...
“Connection Options” on page 2-194
“Microsoft® Access™” on page 2-194
“Microsoft® SQL Server®” on page 2-194
“Oracle” on page 2-195
“MySQL” on page 2-195
“PostgreSQL” on page 2-196
“SQLite” on page 2-196
“Sybase” on page 2-196
“Other ODBC- or JDBC-Compliant Databases” on page 2-196
Connection Options
You can connect to your database using Database Explorer or the command
line. You can perform different actions using Database Explorer than you can
using the command line. For details about deciding which option to use, see
“Connection Options” on page 2-6.
Microsoft Access
• ODBC
- “Connect to Microsoft® Access™ using Database Explorer.” on page 2-21
- “Connect to Microsoft® Access™ using the native ODBC connection
command line.” on page 2-23
2-194
Connecting to a Database
Oracle
• ODBC
- Database Explorer cannot work with the Oracle ODBC driver because
of an issue with the JDBC/ODBC bridge. For details, see “Database
Explorer Error Messages” on page 3-17.
- To connect using the command line, see “Step 4. Connect using the
native ODBC connection command line.” on page 2-50
• JDBC
- “Connect to Oracle using Database Explorer.” on page 2-55
- “Connect to Oracle using the JDBC connection command line.” on page
2-57
MySQL
• ODBC
- “Connect to MySQL using Database Explorer.” on page 2-63
- “Connect to MySQL using the native ODBC connection command line.”
on page 2-65
• JDBC
- “Connect to MySQL using Database Explorer.” on page 2-69
- “Connect to MySQL using the JDBC connection command line.” on page
2-71
2-195
2 Getting Started with Database Toolbox™
PostgreSQL
• ODBC
- “Connect to PostgreSQL using Database Explorer.” on page 2-76
- “Connect to PostgreSQL using the native ODBC connection command
line.” on page 2-78
• JDBC
- “Connect to PostgreSQL using Database Explorer.” on page 2-82
- “Connect to PostgreSQL using the JDBC connection command line.”
on page 2-84
SQLite
• JDBC
- “Connect to SQLite using Database Explorer.” on page 2-88
- “Connect to SQLite using the JDBC connection command line.” on page
2-90
Sybase
• ODBC
- “Connect to Sybase using Database Explorer.” on page 2-97
- “Connect to Sybase using the native ODBC connection command line.”
on page 2-99
• JDBC
- “Connect to Sybase using Database Explorer.” on page 2-103
- “Connect to Sybase using the JDBC connection command line.” on page
2-105
2-196
Connecting to a Database
2-197
2 Getting Started with Database Toolbox™
Selecting Data
In this section...
“Use Database Explorer to Select Data” on page 2-198
“Use the Command Line to Select Data” on page 2-198
“Working with Custom Data Types” on page 2-199
“Running SQL Queries Saved in Scripts or Files” on page 2-199
You can open two different connections to the same database, one using
Database Explorer and another using the command line. If you are working
with large data, use the command line instead of Database Explorer for
maximum performance.
2-198
Selecting Data
If you have a stored procedure you want to run using Database Toolbox, you
can use the runstoredprocedure or exec function.
2-199
2 Getting Started with Database Toolbox™
To fetch data in your database, use the exec and fetch functions.
2-200
Working with Large Data
When working with a native ODBC connection, you might be restricted by the
amount of memory available to MATLAB. You might have to process parts
of your data in MATLAB rather than processing your whole set of data at
once. Use the fetch function to limit the number of rows your query returns
by using the row limit argument. Using a MATLAB script, you can fetch
data in increments using the row limit until all data is retrieved. For an
example, see fetch.
When working with a JDBC connection, you might run into out-of-memory
issues because of JVM heap memory restrictions. To achieve the greatest
performance with importing large sets of data into MATLAB, you might
need to fetch the data in batches by setting database preferences. To assess
your memory needs and for options on running a SQL query that returns
2-201
2 Getting Started with Database Toolbox™
large amounts of data, see “Preference Settings for Large Data Import” on
page 4-19.
If you are using native ODBC, use the fastinsert or insert function for
fastest processing. If you are using a JDBC driver, use datainsert for the
fastest processing to export your data out of MATLAB.
For a comparison of these functions, see “Inserting Data Using the Command
Line” on page 2-200.
2-202
3
3-2
Setting Up JDBC Data Sources
3-3
3 Working with Data Sources
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 the
MAT-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 data
sources dialog box.
4 Click OK to close the Define JDBC data sources dialog box. The data
sources now appear in the Visual Query Builder Data source list.
3-4
Modifying Existing JDBC Data Sources
2 Select the data source in the Define JDBC Data Sources dialog box.
4 Click Add/Update.
5 Click OK to save your changes and close the Define JDBC data sources
dialog box.
3-5
3 Working with Data Sources
2 Click Remove.
3 Click OK to save your changes and close the Define JDBC data sources
dialog box.
3-6
Fetching Data Common Errors
3-7
3 Working with Data Sources
3-8
Fetching Data Common Errors
Modify the
previous
statement to
include your SQL
query instead.
Then process the
resultset object
rs in batches.
3-9
3 Working with Data Sources
All Unable to find JDBC • Path to the JDBC Verify that the path
JDBC-Compliant
driver. driver JAR file is to your JDBC driver
Databases not on the static is added to the
or dynamic class static or dynamic
path. path. Ensure you
provide the correct
• Incorrect driver
JDBC driver name
name provided
for the driver
while using the
and databaseurl
'driver' and
arguments.
'url' syntax.
3-10
Database Connection Error Messages
3-11
3 Working with Data Sources
3-12
Database Connection Error Messages
3-13
3 Working with Data Sources
3-14
Database Connection Error Messages
3-15
3 Working with Data Sources
3-16
Database Explorer Error Messages
3-17
3 Working with Data Sources
of a
table
in the
Database
Browser
pane.
Oracle Error No tables found Database Switch your
occurs in this schema Explorer has a database
inside Consider changing conflict with the connection to use
the the schema. Oracle ODBC a JDBC driver.
Database driver due to For details, see
Browser issues in the “Configuring a
pane. JDBC/ODBC Driver and Data
bridge. Source” on page
2-13.
Oracle Error Unable to get meta Database Switch your
occurs data:[Oracle][ODBC]Driver
Explorer has a database
after not capable. conflict with the connection to use
clicking Oracle ODBC a JDBC driver.
Connect driver due to For details, see
in the issues in the “Configuring a
Connect JDBC/ODBC Driver and Data
to a bridge. Source” on page
Data 2-13.
Source
dialog
box.
Oracle Error Error changing Database Switch your
occurs catalog/schema:[Oracle][ODBC]Driver
Explorer has a database
after not capable conflict with the connection to use
trying Oracle ODBC a JDBC driver.
to driver due to For details, see
change issues in the “Configuring a
the Driver and Data
3-18
Database Explorer Error Messages
3-19
3 Working with Data Sources
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');
3-20
Using the Native ODBC Database Connection
Note The native ODBC interface has a default batch size of 100,000 that
enables acceptable performance. To override this value, you must use
setdbprefs as follows. Set FetchInBatches to yes and set FetchBatchSize
to 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 in
a 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'
3-21
3 Working with Data Sources
colnames = {'productNumber','stockNumber','supplierNumber',...
'unitCost','productDescription'}
colnames =
Columns 1 through 3
Columns 4 through 5
'unitCost' 'productDescription'
Define the data for the row to insert in the cell array coldata.
coldata =
Insert the data in coldata into the productTable with the defined column
names, colnames.
insert(conn,'productTable',colnames,coldata);
Close the cursor object curs, and then close the database connection conn.
close(curs);
close(conn);
3-22
Using the Native ODBC Database Connection
3-23
3 Working with Data Sources
,
database.catalogsdatabase.catalogs ,
and many and many
others) others)
• Use Database • Use Database
Explorer Explorer
(dexplore) (dexplore)
• Close • Close
connection connection
(close) (close)
Underlying C++ Java Java
technology
Memory Restricted Restricted by Restricted by
performance by MATLAB both JVM both JVM
memory, but heap memory heap memory
not JVM heap and MATLAB and MATLAB
memory memory memory
Data access Fastest Slowest Medium
performance
64-bit systems No major issues Several known No major issues
issues with
connectivity and
data access
Data type Long data types Long data types Long data types
support are not supported are supported are supported
(e.g. LONG, BLOB,
etc.)
Note For details about the database.ODBCConnection syntax, see the native
ODBC interface example in database.
3-24
Using the Native ODBC Database Connection
3-25
3 Working with Data Sources
3-26
4
4-2
Getting Started with Visual Query Builder
To start the Visual Query Builder, type querybuilder at the MATLAB prompt.
*Required step
8 Set preferences
for data retrieval.
13 Save, load,
and run queries,
and generate
M-files.
6 Refine query.
7 View SQL
statement.
9* Assign variable
for results.
You can graphically construct and run SQL queries to import database data
using:
4-3
4 Using Visual Query Builder
To create and run a query using Visual Query Builder to import data from a
database into the MATLAB workspace:
1 Select data from a database by clicking the Select button under Data
operation. The data sources that you defined in “Configuring a Driver and
Data Source” on page 2-13 appear.
After you select a data source, the catalog, schema, and tables for your
specified data source appear in the Catalog, Schema, and Tables fields.
4-4
Getting Started with Visual Query Builder
3 Accept the default values <default> for the Catalog and Schema fields.
Setting these fields to the default values indicates that you have not
specified a catalog or schema.
4-5
4 Using Visual Query Builder
Tip To populate the VQB Schema and Catalog fields, you must associate
your user name with schemas or catalogs before starting VQB.
• To specify a Catalog, select one from the list, and then select a schema
from within that catalog. The Schema field updates to reflect your
selections.
• Alternatively, you can select a schema without specifying a catalog; that
is, when the Catalog field set to <default>. The Tables field updates
to reflect the schema you selected.
4 In the Tables list, select salesVolume as the table that contains the data
you want to import.
Tip To select more than one field, hold down the Ctrl or Shift key while
selecting multiple fields. To clear an entry, use Ctrl+click.
VQB adds each field you select to the query in the SQL statement field.
7 Click Execute to run the query and import the data. The Data field
displays information about the query result.
4-6
Getting Started with Visual Query Builder
You supply
input to
these fields.
MATLAB
displays output
in this field.
For details about using the Variables editor, see “View, Edit, and Copy
Variables”.
4-7
4 Using Visual Query Builder
4-8
Getting Started with Visual Query Builder
4-9
4 Using Visual Query Builder
To start the Visual Query Builder, type querybuilder at the MATLAB prompt.
*Required step
5* Select fields
1* Specify Insert. 2* Select data 3 Select 4* Select to which to
source. catalog tables. export data.
and schema.
7 View MATLAB
statement.
6* Specify variable
containing data
to export.
8* Run query.
To build, run, and save a query that exports data from the MATLAB
workspace into new rows in a database:
4-10
Getting Started with Visual Query Builder
4 In the Tables list box, select inventoryTable as the table to which you
want to export data from the MATLAB software.
4-11
4 Using Visual Query Builder
5 In the Fields list box, select productNumber, Quantity, and Price as the
fields to which you want to export data from the MATLAB software.
VQB adds each field you select to the query in the MATLAB command
field.
6 In the MATLAB workspace, assign the data you want to export to a cell
array, export_data.
export_data = {14,1500,18.50};
7 In the MATLAB workspace variable field, enter the name of the variable
containing data to export, export_data. Press Enter or Return to view
the MATLAB command that exports the data.
4-12
Getting Started with Visual Query Builder
4-13
4 Using Visual Query Builder
10 To save this query, select Query > Save and name it export.qry.
4-14
Working with Preferences
Specifying Preferences
Database Toolbox preferences enable you to specify:
• How NULL data in a database is represented after you import it into the
MATLAB 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 Preferences
dialog box appears. Alternatively, from the MATLAB Toolstrip, click
Preferences and select Database Toolbox.
4-15
4 Using Visual Query Builder
4-16
Working with Preferences
Acceptable
Preference Values Description
Read null (default) Specifies how NULL strings appear after being fetched from a
NULL database.
strings as:
Read Nan (default) Specifies how NULL numbers appear after being fetched from a
NULL database. If you accept the default value for this field, NULL data
numbers imported from databases into the MATLAB workspace appears
as: as NaN. Setting this field to 0 causes NULL data imported into the
MATLAB workspace to appear as 0s.
Write null (default) Specifies how NULL strings appear after being exported to a
NULL database. This setting does not apply to Database Explorer
strings as: (dexplore).
Write Nan (default) Specifies how NULL numbers appear after being exported to a
NULL database. This setting does not apply to Database Explorer
numbers (dexplore).
as:
Data cell array, Select a data format based on the type of data you are importing,
return numeric, memory considerations, and your preferred method of working
format structure, or with retrieved data.
dataset
• cellarray (default) — Imports nonnumeric data into
MATLAB cell arrays.
• numeric — Imports data into MATLAB matrix of doubles.
Nonnumeric data types are considered NULL and appear as
specified in the Read NULL numbers as: setting. Use
only when data to retrieve is in numeric format, or when
nonnumeric data to retrieve is not relevant.
• structure — Imports data into a MATLAB structure. Use for
all data types. Facilitates working with returned columns.
• dataset — Imports data into MATLAB dataset objects. This
option requires Statistics Toolbox™.
This setting does not apply to Database Explorer (dexplore).
If you are using Database Explorer, the data return format is
4-17
4 Using Visual Query Builder
Acceptable
Preference Values Description
3 Click OK. For details about Preferences, see the setdbprefs function
reference page.
4-18
Preference Settings for Large Data Import
• If your data (n rows) will fit in a MATLAB variable, then will all your data
fit 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 JVM
heap. Use the following preference setting:
setdbprefs('FetchInBatches','yes')
setdbprefs('FetchBatchSize','<h>')
setdbprefs('FetchInBatches','yes')
setdbprefs('FetchBatchSize','<h>')
4-19
4 Using Visual Query Builder
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 of
data, you do not need to change these settings because the native ODBC
interface always fetches data in batches of 100,000 rows. You can still
override the default batch size by setting 'FetchInBatches' to 'yes'
and 'FetchBatchSize' to a number of your choice. Note that JVM heap
memory restrictions do not apply in this case since the native ODBC
interface is a C++ API.
It is important to have an idea of the size of data that you are looking to
import from a database. Finding the size of the table(s) in the database can be
misleading because MATLAB representation of the same data is most likely
going to consume more memory. For instance, say your table has one numeric
column and one text column and you are looking to import it in a cell array.
Here is how you can estimate the total size.
If you are looking to import a thousand rows of the table, the approximate size
in MATLAB would be 156 * 1000 = 156 KB. You can replicate this process for
a structure or a dataset depending on which data type you want to import the
data in. Once you know the size of data to be imported in MATLAB, you can
4-20
Preference Settings for Large Data Import
setdbprefs('FetchInBatches','yes')
setdbprefs('FetchBatchSize','<h>')
4-21
4 Using Visual Query Builder
results = runsqlscript(conn,'<filename>.sql','rowInc','<m>')
Once you are done processing these m rows, you can import the next m
rows using the same commands. Keep in mind, however, that using the
same cursor object curs for this results in the first curs being overwritten,
including everything in curs.Data.
To use automated batching to fetch where h rows fit in the JVM heap:
setdbprefs('FetchInBatches','yes')
setdbprefs('FetchBatchSize','<h>')
results = runsqlscript(conn,'<filename>.sql')
Note that when you use automated batching and do not supply the rowLimit
parameter to fetch or the rowInc parameter to runsqlscript, a count query
4-22
Preference Settings for Large Data Import
curs = fetch(curs,<n>)
or
results = runsqlscript(conn,'<filename>.sql','rowInc','<n>')
setdbprefs('FetchInBatches','no')
If using fetch:
curs = fetch(curs);
results = runsqlscript(conn,'<filename>.sql')
4-23
4 Using Visual Query Builder
• Enter the variable name to which to assign the query results in the
MATLAB Command Window.
• Double-click the variable in the VQB Data area to view the data in the
Variables editor.
The examples in this section use the saved query basic.qry. To load and
configure this query:
3 In the Load SQL Statement dialog box, select basic.qry from the File
name field and click Open.
1 Execute basic.qry.
4-24
Displaying Query Results
This display shows only unique values for each field, so you should not
read each row as a single record. In this example, there are 10 entries for
StockNumber, eight entries for January and February, and 10 entries
for March. The number of entries in each field corresponds to the number
of unique values in the field.
4-25
4 Using Visual Query Builder
The data associated with the selected value appears in bold font and is
connected with a dotted line. The data shows that sales for item 400876 are
3000 in January, 2400 in February, and 1500 in March.
4-26
Displaying Query Results
4-27
4 Using Visual Query Builder
2 Select a type of chart from the Charts list. In this example, choose a pie
chart by specifying pie.
A preview of the pie chart, with each stock item displayed in a different
color, appears at the bottom of the dialog box.
4-28
Displaying Query Results
3 Select the data to display in the chart from the X data, Y data, and Z
data list boxes. In this example, select March from the X data list box to
display 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 the
Show legend check box.
A legend appears in the chart preview. Drag and move the legend in the
preview as needed.
4-29
4 Using Visual Query Builder
The query results appear as a table in a Web browser. Each row represents a
record from the database. In this example, sales for item 400876 are 3000 in
January, 2400 in February, and 1500 in March.
Tip Because some browsers do not start automatically, you may need to open
your Web browser before displaying the query results.
4-30
Displaying Query Results
4-31
4 Using Visual Query Builder
3 Open the report template for editing by clicking Open a Report file or
stylesheet.
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:
4-32
Displaying Query Results
c Click Apply.
4-33
4 Using Visual Query Builder
Each row represents a record from the database. For example, sales for
item 400876 are 3000 in January, 2400 in February, and 1500 in March.
For details about the MATLAB Report Generator product, click the Help
button in the Report Explorer.
4-34
Displaying Query Results
Tip Because some browsers are not configured to launch automatically, you
may need to open your Web browser before displaying the report.
4-35
4 Using Visual Query Builder
Note For details about advanced query options, select Help in any of the
dialog boxes for the options.
4-36
Fine-Tuning Queries Using Advanced Query Options
4-37
4 Using Visual Query Builder
The value 3000 appears three times in All, but appears only once in
Distinct.
1 Load basic.qry.
5 In Fields, select the field whose values you want to restrict, StockNumber.
a Select Relation.
4-38
Fine-Tuning Queries Using Advanced Query Options
d Click Apply.
The clause that you defined, StockNumber > 400000, appears in the
Current clauses area.
4-39
4 Using Visual Query Builder
7 Add the condition that StockNumber must also be less than 500000.
d Click Apply.
i Click Apply.
8 Click OK.
The WHERE Clauses dialog box closes. The Where field and SQL
statement display the Where Clause you specified.
10 Click Execute.
4-40
Fine-Tuning Queries Using Advanced Query Options
Grouping Statements
Use the WHERE Clauses dialog box to group query statements. In this
example, modify basic_where.qry to retrieve data where sales in January,
February, or March exceed 1500 units, if sales in each month exceed 1000
units.
To modify basic_where.qry:
4-41
4 Using Visual Query Builder
c In Fields, select January. For Relation, select > and enter 1500 in its
field. For Operator, select OR. Click Apply.
d Repeat step c twice, specifying February and March in Fields.
3 Group the criteria that require sales in each month to exceed 1500 units.
a In Current clauses, select the statement January > 1500 OR. Press
Shift+click to select February > 1500 OR and March > 1500 also.
b Click Group.
4-42
Fine-Tuning Queries Using Advanced Query Options
4 Modify the query to retrieve data if sales in each month exceed 1000 units.
c Select January in Fields. Select > for Relation and enter 1000 in its
field. Select AND for Operator. Click Apply.
d Repeat step c twice, specifying February and March in Fields.
4-43
4 Using Visual Query Builder
e Click OK.
The WHERE Clauses dialog box closes. The SQL statement dialog box
displays the modified where clause.
4-44
Fine-Tuning Queries Using Advanced Query Options
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 their
grouping is removed.
4-45
4 Using Visual Query Builder
1 Load basic_where.qry.
5 Enter values for the Sort key number and Sort order fields for the
appropriate Fields.
d Click Apply.
January ASC
4-46
Fine-Tuning Queries Using Advanced Query Options
d Click Apply.
January ASC
February ASC
7 To specify March as the third sort field and display results in descending
order:
a In Fields, select March.
d Click Apply.
January ASC
February ASC
March DESC
8 Click OK.
The ORDER BY Clauses dialog box closes. The Order by field and the
SQL statement in VQB display the specified Order By clause.
4-47
4 Using Visual Query Builder
For B, results are first sorted by January sales, in ascending order. The
lowest value for January sales, 1200 (for item number 400455), appears
first. 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 sales
appear in ascending order: 1500, 2400, and 2400 respectively.
For items 400314 and 400876, February sales were 2400, so the third
sort key, March sales, applies. March sales appear in descending order:
1800 and 1500, respectively.
4-48
Fine-Tuning Queries Using Advanced Query Options
1 From the Fields list box, select the entry whose value to restrict.
• To edit a clause:
a Select the clause from Current clauses and click Edit.
c Click Apply.
• To group clauses:
4-49
4 Using Visual Query Builder
8 Click OK.
The HAVING Clauses dialog box closes. The SQL statement in the Visual
Query Builder dialog box updates to reflect the specified having clause.
2 For January:
d Click Apply.
3 For February:
4-50
Fine-Tuning Queries Using Advanced Query Options
4 Click OK.
The HAVING Clauses dialog box closes. The SQL statement field in the
VQB dialog box reflects the specified Having clause.
C =
[3000] [2400]
[5000] [3500]
This example uses basic.qry, which you created by selecting Query > Save
and saving your query as basic.qry in the File name field.
The salesVolume table has sales volumes and stock number fields, but no
product description field. The productTable has product description and
stock number fields, but no sales volumes. This example retrieves the stock
4-51
4 Using Visual Query Builder
number for the product whose description is Building Blocks from the
productTable table. It then gets the sales volume values for that stock
number from the salesVolume table.
1 Load basic.qry.
2 Set the Data return format Preference to cellarray and Read NULL
numbers as to NaN.
4 Click Subquery.
4-52
Fine-Tuning Queries Using Advanced Query Options
6 In Fields, select stockNumber, the field that is common to this table and
the table from which you are retrieving results.
d In the field to the right of the drop-down list, enter 'Building Blocks'.
e Click Apply.
4-53
4 Using Visual Query Builder
This updates the Current clauses area using the subquery criteria
specified in steps 3 through 8.
4-54
Fine-Tuning Queries Using Advanced Query Options
The WHERE Clauses dialog box closes. The SQL statement in the VQB
dialog box updates.
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 description
Building Blocks, although that is not evident from the results. Create
and run a query to verify that the product description is Building Blocks:
a For Data source, select dbtoolboxdemo.
e Click Execute.
4-55
4 Using Visual Query Builder
The results show that item 400345 has the product description Building
Blocks. In the next section, you create a query that includes product
description in the results.
Note You can include only one subquery in a query using VQB; you can
include multiple subqueries using Database Toolbox functions.
The salesVolume table has sales volume and stock number fields, but
no product description field. The productTable table has product
description and stock number fields, but no sales volume field. To create
a query that retrieves data from both tables and equates the stock number
from productTable with the stock number from salesVolume:
4-56
Fine-Tuning Queries Using Advanced Query Options
1 Set the Data return format preference to cellarray and the Read
NULL numbers as preference to NaN.
4 In Tables, select the tables from which you want to retrieve data. For this
example, press Ctrl+click and select both productTable and salesVolume.
• productTable.productDescription
• salesVolume.January
• salesVolume.February
• salesVolume.March
4-57
4 Using Visual Query Builder
f Click OK to close the WHERE Clauses dialog box. The Where field and
SQL statement in VQB display the Where clause.
P1 =
4-58
Fine-Tuning Queries Using Advanced Query Options
4-59
4 Using Visual Query Builder
4-60
Retrieving BINARY and OTHER Data Types
A =
photo = A{1,2};
12 Run the sample program parsebinary, which writes the retrieved data to
a file, strips ODBC header information, and displays photo as a bitmap
image.
cd I:\MATLABFiles\myfiles
parsebinary(photo, 'BMP');
4-61
4 Using Visual Query Builder
4-62
Importing and Exporting Boolean Data
This example imports data from the Invoice table in the dbtoolboxdemo
database into the MATLAB workspace.
D =
[ 2101] [0]
[ 3546] [1]
[33116] [1]
[34155] [0]
[34267] [1]
4-63
4 Using Visual Query Builder
[37197] [1]
[37281] [0]
[41011] [1]
[61178] [0]
[62145] [1]
4-64
Importing and Exporting Boolean Data
10 In the VQB Data area, double-click D to view its contents in the Variables
editor.
4-65
4 Using Visual Query Builder
I.InvoiceNumber{1,1}=456789;
I.Paid{1,1}=logical(0);
I.InvoiceNumber{2,1}=987654;
I.Paid{2,1}=logical(1);
View the table in Microsoft Access to verify that the data was correctly
inserted.
4-66
Importing and Exporting Boolean Data
4-67
4 Using Visual Query Builder
% Make connection to database. Note that the password has been omitted.
% Using ODBC driver.
conn = database('dbtoolboxdemo','','password');
4-68
Saving Queries in Files
myVar = e.Data
Saving Queries
1 Click Query > Save. The Save SQL Statement dialog box appears.
2 Enter a name (without spaces) for the query into the File name field and
click Save. Save the query as basic.qry.
4-69
4 Using Visual Query Builder
Note When you save a Select query (a query that imports data), MATLAB
does not save your specified preferences or the workspace variable that
contains the query results. This prevents you from inadvertently overwriting
an existing variable in the MATLAB workspace when you run a saved query.
When you save an Insert query (a query that exports data), MATLAB saves
the workspace variable whose data you exported, but does not save your
preferences.
2 Select the name of the query you want to load and click Open. The VQB
fields reflect the values for the saved query.
Tip You can generate a file that runs the query from the MATLAB
Command Window in the future. For details, see “Saving Queries in Files”
on page 4-68 in the Database Toolbox documentation.
Editing Queries
Edit a query using one of the following options:
4-70
Saving Queries in Files
4-71
4 Using Visual Query Builder
4-72
Using Database Explorer
setdbprefs('JDBCDataSourceFile','')
4-73
4 Using Visual Query Builder
Data sources interact with ODBC drivers or JDBC drivers. An ODBC driver is
a standard Microsoft Windows interface that enables communication between
database management systems and SQL-based applications. A JDBC driver
is a standard interface that enables communication between applications
based on Oracle Java and database management systems.
This figure illustrates how drivers interact with Database Toolbox software.
Tip Some Windows systems support both ODBC and JDBC drivers. On such
systems, JDBC drivers generally provide better performance than ODBC
drivers because the JDBC/ODBC bridge is not used to access databases.
1 Set up the data sources that are provided with Database Toolbox.
4-74
Using Database Explorer
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 4-75.
• If you are using a JDBC driver, see “Configure JDBC Data Sources”
on page 4-80.
Note You might need to convert the database to the version of Access you
are currently running. For example, beginning in Microsoft Access 2007,
you see the option to save as *.accdb. For details, consult your database
administrator.
4-75
4 Using Visual Query Builder
dexplore
If no data sources are set up, a message box opens. Click OK to close it.
Otherwise, the Connect to a Data Source dialog box opens. Click Cancel to
close this dialog box.
3 Click the Database Explorer tab and then select New > ODBC to open
the ODBC Data Source Administrator dialog box to define the ODBC data
source.
4-76
Using Database Explorer
A list of installed ODBC drivers appears in the Create New Data Source
dialog box.
4-77
4 Using Visual Query Builder
The ODBC Microsoft Access Setup dialog box for your driver opens. The
dialog box for your driver might differ from the following.
4-78
Using Database Explorer
7 Select the database for this data source to use. For some drivers, you can
skip this step. If you are unsure about skipping this step, consult your
database administrator.
a In the ODBC Microsoft Access Setup dialog box, click Select.
b Specify the database you want to use. For the dbtoolboxdemo data
source, select tutorial.mdb.
c If your database is on a system to which your PC is connected:
9 Repeat steps 6 through 8 with the following changes to define the data
source for any additional databases that you want to use.
4-79
4 Using Visual Query Builder
1 Find the name of the JDBC driver file. This file is provided by your
database 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 database
administrator.
4-80
Using Database Explorer
setdbprefs('JDBCDataSourceFile', '')
Then follow these instructions to set up the JDBC data source using
Database Explorer.
2 Specify the location of the JDBC drivers file in the MATLAB Java class
path by adding this file’s path to the javaclasspath.txt file. MATLAB
loads the static class path at the start of each session. The static path
offers better class loading performance than the dynamic path. To add
folders to the static path, create the file javaclasspath.txt, and then
restart MATLAB.
prefdir
Each line in the file is the path name of a folder or JAR file. For example:
d:\work\javaclasses
Note MATLAB reads the static class path only at startup. If you edit
javaclasspath.txt or change your .class files while MATLAB is
running, you must restart MATLAB to put those changes into effect.
4-81
4 Using Visual Query Builder
dexplore
5 Click the Database Explorer tab and then select New > JDBC to open
the Create a New JDBC data source dialog box.
4-82
Using Database Explorer
6 Use the following table to set up JDBC drivers for use with Database
Explorer.
a Using the Create a New JDBC data source dialog box, this table describes
the fields that you use to define your JDBC data source. For examples
of syntax used in these fields, see “JDBC Driver Name and Database
Connection URL” on page 6-42 on the database function reference page.
4-83
4 Using Visual Query Builder
Field Description
Data Source The name you assign to the data source. For some
Name databases, Name must match the name of the
database as recognized by the machine it runs on.
Vendor The vendor’s name for the data source. When using
Other:
• Driver — The JDBC driver name (sometimes
referred to as the class that implements the Java
SQL driver for your database).
• URL — The JDBC URL object, of the form
jdbc:subprotocol:subname. subprotocol, is
a database type. subname can contain other
information used by Driver, such as the location of
the database and/or a port number. It can take the
form //hostname:port/databasename.
4-84
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 Database
Explorer, the New file to store JDBC connection parameters dialog box
opens. Use this dialog box to create a MAT-file that saves your specified
data source information for future Database Explorer sessions.
Navigate to the folder where you want to put the MAT-file, specify a
name for it that includes a .mat extension, and click Save.
d Test the connection by clicking Test.
Note You can use tabs in Database Explorer to access different data
sources. All of the data sources created using Database Explorer are
stored in a single MAT-file for easy access. This MAT-file name is stored
in setdbprefs('JDBCDataSourceFile') and is valid for all MATLAB
sessions.
dexplore
2 Select your data source from the Connect to a Data Source dialog box or
click Cancel and then click the Database Explorer tab and then click
Connect to select your data source.
4-85
4 Using Visual Query Builder
3 Select your data source from the Data Sources list and enter your user
name and password.
4-86
Using Database Explorer
(Continued)
4-87
4 Using Visual Query Builder
(Continued)
4-88
Using Database Explorer
4-89
4 Using Visual Query Builder
3 Click OK.
1 Display data in the Data Preview pane by opening the database table
of interest in the Database Browser pane. When a database table is
selected in the Database Browser pane, it is highlighted and there is a
corresponding entry in the SQL Criteria panel on the Database Explorer
Toolstrip. The SQL Criteria panel is where you enter query conditions
for 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 in
the Data Preview pane but does update the SQL Criteria panel.
• Select (All) to choose all table columns and display them in the Data
Preview pane.
• Select specific check boxes to choose individual table columns and
display them in the Data Preview pane.
Note The order of the columns in the Data Preview pane matches the
order in which you select them in the Database Browser pane.
4-90
Using Database Explorer
2 Select (All) to choose all database columns or select check boxes for specific
table columns.
4-91
4 Using Visual Query Builder
The Data Preview pane displays a limited number of rows. The total
number of rows actually selected in the database appears at the right of
the display. You can change the display size by clicking Preferences and
adjusting the Data Preview size.
1 Display data in the Data Preview pane by opening the desired database
table in the Database Browser pane. The SQL Criteria panel on the
Database Explorer Toolstrip is updated.
4-92
Using Database Explorer
2 When you select additional tables in the Database Browser pane, the
SQL Criteria panel is updated.
4-93
4 Using Visual Query Builder
4-94
Using Database Explorer
which table column to join the selected tables. The join results appear
in the Data Preview pane.
4-95
4 Using Visual Query Builder
4-96
Using Database Explorer
Using the Database Browser pane and the SQL Criteria panel, you can
define query conditions and display the results in the Data Preview pane.
Each row in the SQL Criteria panel has drop-down controls to define SQL
query conditions. You can create SQL query conditions that span multiple
rows in the SQL Criteria panel.
Tip: If you do not use the Enter or Tab key to apply the query condition,
selecting Import > Import applies the condition to the Data Preview pane
and imports the data into a MATLAB variable. If there is no data to satisfy
the condition, then the Nothing to import error message appears.
Each row in the SQL Criteria panel has four columns to define your SQL
query.
4-97
4 Using Visual Query Builder
4-98
Using Database Explorer
4-99
4 Using Visual Query Builder
apply the condition. If you use the LIKE or NOT LIKE SQL operator to
match a string, the ' ' are automatically added to the string value.
Note If you click + to add a new query condition between two previously
entered conditions, the available query options do not always produce
semantically correct SQL statements. In this case, you must ensure that
your query options are semantically correct. For best results using the SQL
Criteria panel, add and apply your conditions in sequence.
4-100
Using Database Explorer
4-101
4 Using Visual Query Builder
4-102
Using Database Explorer
3 From the SQL Criteria panel, in the first (topmost) condition, change
the first combo box for condition type to LEFT JOIN. Change the second
combo box to suppliers.SupplierNumber. Change the last combo box to
producttable.SupplierNumber. A left join, with the suppliers table on
the left, implies that all the rows in the suppliers table are included in the
final result, and the rows in suppliers that do not have a match with any
row 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 that there
is a null in productDescription and a NaN for unitCost. This is because
there is no product that is supplied by The Great Teddy Bear Company. If
the condition type were INNER JOIN instead of LEFT JOIN, this row
would not appear in the final result.
4-103
4 Using Visual Query Builder
4-104
Using Database Explorer
4 From the SQL Criteria pane, click + at the end of the LEFT JOIN
condition to add a new query condition. Change the first combo box
to WHERE, the second to suppliers.Country, and the third to NOT
LIKE. In the last text box, type United States and then enter the new
condition using the Enter or Tab key. The query results appear in the
Data Preview pane.
4-105
4 Using Visual Query Builder
4-106
Using Database Explorer
5 Enter the variable name as data in the text box untitled located above the
table preview, and select Import > Import to import the data displayed
in the Data Preview pane into MATLAB as a variable named data. For
details about using the MATLAB Variables editor, see “View, Edit, and
Copy Variables”.
4-107
4 Using Visual Query Builder
4-108
Using Database Explorer
3 The new data source appears in a new tab in the Database Browser pane.
You can change databases by clicking the associated tab.
You can only use Database Explorer to create SQL queries for a single
database at a time.
In addition, you can work with a different catalog and schema on the same
database server as the one connected to your current data source. To change
to a different catalog and schema:
• Select the catalog/schema from the drop-down list in the address bar of the
Database Browser. For a database system like Microsoft SQL Server that
has a hierarchy of catalogs and schemas, make sure you choose the correct
value for both to access data in your tables.
2 Name the MATLAB variable by entering it in the untitled text box in the
Data Preview pane.
3 Use the Imported Data panel to define the data type for a MATLAB
variable to store the data displayed in the Data Preview pane. Supported
data types are:
• Cell Array
• Numeric
• Structure
• Table
4-109
4 Using Visual Query Builder
4 Select Import > Import to import the data displayed in the Data
Preview pane.
4-110
Using Database Explorer
4-111
4 Using Visual Query Builder
5 (Optional) Display the imported data in the MATLAB workspace using the
Variables editor. For details about using the Variables editor, see “View,
Edit, and Copy Variables”.
4-112
Using Database Explorer
1 Use the Database Browser pane to select data from a single table or
multiple tables. Then use the SQL Criteria panel to create queries and
display the results in the Data Preview pane.
2 After you have created a query using the SQL Criteria panel, select
Import > Generate SQL to display the SQL code in the MATLAB Editor.
3 Save the SQL code to a .txt or .sql file. You can then use the SQL
statements to manually rebuild a query using the SQL Criteria panel.
Alternatively, you can use the .sql file to import data programmatically
into MATLAB by using runsqlscript.
1 Connect to a data source and then use the Database Browser pane to
select data from a single table or use the SQL Criteria panel to create a
query and display the results in the Data Preview pane.
4-113
4 Using Visual Query Builder
3 Save the MATLAB code to a file. You can run this code file from the
command line to connect to a data source and run a query.
4-114
5
Follow these simple examples consecutively when you first start using the
product. Once you are familiar with Database Toolbox usage, refer to these
examples as needed.
5-2
Importing Data from Databases
1 Before you connect to a database, set the maximum time that you want to
allow the MATLAB software session to try to connect to a database to 5
seconds.
logintimeout(5)
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
5-3
5 Using Database Toolbox™ Functions
5 The returned data contains strings, so you must convert it to a format that
supports 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 later
time, close the cursor and the connection as follows:
close(curs);
close(conn);
5-4
Viewing Information About Imported Data
• attr
• close
• cols
• columnnames
• rows
• width
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
numrows = rows(curs)
numrows =
10
numcols = cols(curs)
numcols =
1
5-5
5 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 specified
column number:
colsize = width(curs, 1)
colsize =
50
attributes = attr(curs)
attributes =
fieldName: 'productDescription'
typeName: 'VARCHAR'
typeValue: 12
columnWidth: 50
precision: []
scale: []
currency: 'false'
readOnly: 'false'
nullable: 'true'
Message: []
close(curs);
8 Continue with the next example. To stop working now and resume working
on the next example at a later time, close the connection.
5-6
Viewing Information About Imported Data
close(conn);
5-7
5 Using Database Toolbox™ Functions
• get
• fastinsert
• setdbprefs
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
setdbprefs('DataReturnFormat','numeric')
3 Import ten rows of data the March column of data from the salesVolume
table.
5-8
Exporting Data to New Record in Database
AA = curs.Data
AA =
981
1414
890
1800
2600
2800
800
1500
1000
821
5 Calculate the sum of the March sales and assign the result to the variable
sumA:
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'
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 yearlySales
table in the dbtoolboxdemo database. Assign the cell array containing the
column names to the variable colnames:
colnames = {'Month','salesTotal'};
5-9
5 Using Database Toolbox™ Functions
8 Use the get function to determine the current status of the AutoCommit
database flag. This status determines whether the exported data is
automatically committed to the database. If the flag is off, you can undo
an update; if it is on, data is automatically committed to the database.
get(conn, 'AutoCommit')
ans =
on
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
close(curs);
12 Continue with the next example (“Replacing Existing Database Data with
Exported Data” on page 5-12). To stop now and resume working with the
next example at a later time, close the connection.
5-10
Exporting Data to New Record in Database
close(conn);
5-11
5 Using Database Toolbox™ Functions
• close
• update
colnames = {'Month'};
newdata = {'March2010'}
newdata =
'March2010'
update(conn,'yearlySales',colnames,newdata,whereclause)
5-12
Replacing Existing Database Data with Exported Data
close(conn);
5-13
5 Using Database Toolbox™ Functions
1 Imports monthly sales figures for all products from the dbtoolboxdemo
data source into the MATLAB workspace.
• fastinsert
• setdbprefs
1 Ensure that the dbtoolboxdemo data source is writable, that is, not read
only.
2 Use the database function to connect to the data source, assigning the
returned connection object as conn. Pass the following arguments to this
function:
• dbtoolboxdemo, the name of the data source
• username and password, which are passed as empty strings because no
user name or password is required to access the database
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, 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 read
from the database are converted to 0 in the MATLAB workspace.
setdbprefs...
5-14
Exporting Multiple Records from the MATLAB® Workspace
({'NullNumberRead';'DataReturnFormat'},{'0';'numeric'})
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'
curs.Data(:,2)
ans =
1400
2400
1800
3000
4300
5000
1200
3000
3000
0
5-15
5 Using Database Toolbox™ Functions
7 Assign the dimensions of the matrix containing the fetched data set to
m and n.
[m,n] = size(curs.Data)
m =
10
n =
13
8 Use m and n to compute monthly totals. The variable tmp is the sales
volume for all products in a given month c. The variable monthly is the
total 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, where
column 2 is the sales volume for January.
for c = 2:n
tmp = curs.Data(:,c);
monthly(c-1,1) = sum(tmp(:));
end
monthly
25100
15621
14606
11944
9965
8643
6525
5899
8632
13170
48345
172000
9 Create a string array containing the column names into which you want to
insert the data, and assign the array to the variable colnames.
colnames{1,1} = 'salesTotal';
5-16
Exporting Multiple Records from the MATLAB® Workspace
11 To verify that the data was imported correctly, in Microsoft Access, view
the yearlySales table from the tutorial database.
close(curs);
close(conn);
5-17
5 Using Database Toolbox™ Functions
javaaddpath 'path\ojdbc5.jar';
conn = database('databasename','user','password', ...
'oracle.jdbc.driver.OracleDriver', ...
'jdbc:oracle:thin:@machine:port:databasename');
A = {100000.00,'KGreen','06/22/2011','Challengers'};
A = A(ones(10000,1),:);
5-18
Exporting Data Using the Bulk Insert Command
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);
e = exec(conn, ...
'create or replace directory ext as ''C:\\Temp''');
close(e)
8 Create a temporary table and bulk insert it into the table BULKTEST.
5-19
5 Using Database Toolbox™ Functions
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'
close(conn)
javaaddpath 'path\sqljdbc4.jar';
conn = database('databasename','user','password', ...
'com.microsoft.sqlserver.jdbc.SQLServerDriver', ...
'jdbc:sqlserver://machine:port;
database=databasename');
5-20
Exporting Data Using the Bulk Insert Command
A = {100000.00,'KGreen','06/22/2011','Challengers'};
A = A(ones(10000,1),:);
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);
5-21
5 Using Database Toolbox™ Functions
results =
Attributes: []
Data: {10000x4 cell}
DatabaseObject: [1x1 database]
RowLimit: 0
SQLQuery: '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'
close(conn)
javaaddpath 'path\mysql-connector-java-5.1.13-bin.jar';
conn = database('databasename', 'user', 'password', ...
'com.mysql.jdbc.Driver', ...
'jdbc:mysql://machine:port/databasename');
5-22
Exporting Data Using the Bulk Insert Command
A = {100000.00,'KGreen','06/22/2011','Challengers'};
A = A(ones(10000,1),:);
Note MySQL reads files saved locally, even if you are connecting to a
remote 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);
5-23
5 Using Database Toolbox™ Functions
results =
Attributes: []
Data: {10000x4 cell}
DatabaseObject: [1x1 database]
RowLimit: 0
SQLQuery: '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'
close(conn)
5-24
Retrieving Image Data Types
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
setdbprefs('DataReturnFormat','cellarray');
3 Import the InvoiceNumber and Receipt columns of data from the Invoice
table.
curs.Data
ans =
5-25
5 Using Database Toolbox™ Functions
Note Some OTHER data type fields may be empty, indicating that the data
could not pass through the JDBC/ODBC bridge.
receipt = curs.Data{1,2};
6 Run parsebinary. This program writes the retrieved data to a file, strips
ODBC header information from it, and displays receipt as a bitmap image
in a figure window. Ensure that your current folder is writable so that the
output of parsebinary can be written to it.
cd 'I:\MATLABFiles\myfiles
parsebinary(receipt, 'BMP');
For details about parsebinary, enter help parsebinary or view its file in
the MATLAB Editor/Debugger by entering open parsebinary.
5-26
Working with Database Metadata
Accessing Metadata
In this example, you use the following Database Toolbox functions to access
metadata:
• dmd
• get
• supports
• tables
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
5-27
5 Using Database Toolbox™ Functions
dbmeta = dmd(conn)
3 Use the get function to assign database properties data, dbmeta, to the
variable v:
v = get(dbmeta)
v =
AllProceduresAreCallable: 1
AllTablesAreSelectable: 1
DataDefinitionCausesTransactionCommit: 1
DataDefinitionIgnoredInTransactions: 0
DoesMaxRowSizeIncludeBlobs: 0
Catalogs: {4x1 cell}
CatalogSeparator: '.'
CatalogTerm: 'DATABASE'
DatabaseProductName: 'ACCESS'
DatabaseProductVersion: '04.00.0000'
DefaultTransactionIsolation: 2
DriverMajorVersion: 2
DriverMinorVersion: 1
DriverName: [1x31 char]
DriverVersion: '2.0001 (04.00.6200)'
ExtraNameCharacters: [1x29 char]
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
5-28
Working with Database Metadata
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: [1x461 char]
StringFunctions: [1x91 char]
StoresLowerCaseIdentifiers: 0
StoresLowerCaseQuotedIdentifiers: 0
StoresMixedCaseIdentifiers: 0
StoresMixedCaseQuotedIdentifiers: 1
StoresUpperCaseIdentifiers: 0
StoresUpperCaseQuotedIdentifiers: 0
SystemFunctions: ''
TableTypes: {13x1 cell}
TimeDateFunctions: [1x111 char]
TypeInfo: {16x1 cell}
URL: ...
'jdbc:odbc:dbtoolboxdemo'
UserName: 'admin'
NullPlusNonNullIsNull: 0
NullsAreSortedAtEnd: 0
NullsAreSortedAtStart: 0
NullsAreSortedHigh: 0
NullsAreSortedLow: 1
UsesLocalFilePerTable: 0
UsesLocalFiles: 1
5-29
5 Using Database Toolbox™ Functions
Tip For details about the database metadata properties returned by get,
see the methods of the DatabaseMetaData object on the Oracle Java Web
site:
http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html.
5-30
Working with Database Metadata
4 Some information is too long to fit in the display area of the field, so the
size of the field data appears instead. The Catalogs element is shown as a
4-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: 1
AlterTableWithDropColumn: 1
ANSI92EntryLevelSQL: 1
ANSI92FullSQL: 0
ANSI92IntermediateSQL: 0
CatalogsInDataManipulation: 1
CatalogsInIndexDefinitions: 1
CatalogsInPrivilegeDefinitions: 0
CatalogsInProcedureCalls: 0
CatalogsInTableDefinitions: 1
ColumnAliasing: 1
Convert: 1
CoreSQLGrammar: 0
CorrelatedSubqueries: 1
DataDefinitionAndDataManipulationTransactions: 1
DataManipulationTransactionsOnly: 0
DifferentTableCorrelationNames: 0
ExpressionsInOrderBy: 1
ExtendedSQLGrammar: 0
FullOuterJoins: 0
GroupBy: 1
GroupByBeyondSelect: 1
GroupByUnrelated: 0
IntegrityEnhancementFacility: 0
LikeEscapeClause: 0
LimitedOuterJoins: 0
5-31
5 Using Database Toolbox™ Functions
MinimumSQLGrammar: 1
MixedCaseIdentifiers: 1
MixedCaseQuotedIdentifiers: 0
MultipleResultSets: 0
MultipleTransactions: 1
NonNullableColumns: 0
OpenCursorsAcrossCommit: 0
OpenCursorsAcrossRollback: 0
OpenStatementsAcrossCommit: 1
OpenStatementsAcrossRollback: 1
OrderByUnrelated: 0
OuterJoins: 1
PositionedDelete: 0
PositionedUpdate: 0
SchemasInDataManipulation: 0
SchemasInIndexDefinitions: 0
SchemasInPrivilegeDefinitions: 0
SchemasInProcedureCalls: 0
SchemasInTableDefinitions: 0
SelectForUpdate: 0
StoredProcedures: 1
SubqueriesInComparisons: 1
SubqueriesInExists: 1
SubqueriesInIns: 1
SubqueriesInQuantifieds: 1
TableCorrelationNames: 1
Transactions: 1
Union: 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 details about properties that the database supports, see the
methods of the DatabaseMetaData object on the Oracle Java Web site at
http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html.
5-32
Working with Database Metadata
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'
close(conn)
For details, see the resultset and rsmd function reference pages.
5-33
5 Using Database Toolbox™ Functions
• driver
• drivermanager
• get
• isdriver
• set
c = database('orc1','scott','tiger',...
'oracle.jdbc.driver.OracleDriver',...
'jdbc:oracle:thin:@144.212.123.24:1822:');
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 the
driver object.
v = get(d)
v =
MajorVersion: 1
5-34
Using Driver Functions
MinorVersion: 0
isdriver(d)
ans =
1
This result shows that d is a valid JDBC driver object. If it is a not valid
JDBC driver object, the returned result is 0.
dm = drivermanager
v = get(dm)
v =
Drivers: {'sun.jdbc.odbc.JdbcOdbcDriver@761630' ...
[1x38 char]}
LoginTimeout: 0
LogStream: []
7 Set the LoginTimeout value to 10 for all drivers loaded during this session.
set(dm,'LoginTimeout',10)
v = get(dm)
v =
Drivers: {'sun.jdbc.odbc.JdbcOdbcDriver@761630'}
LoginTimeout: 10
LogStream: []
5-35
5 Using Database Toolbox™ Functions
• Cursor
• Database
• Database metadata
• Driver
• Drivermanager
• Resultset
• Resultset metadata
Each object has its own method folder, whose name begins with an @ sign, in
the matlabroot/toolbox/database/database folder. Functions in the folder
for each object provide methods for operating on the object.
5-36
About Database Toolbox™ Objects and Methods
This example uses the fetch function to create a cursor object curs.
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]
curs.Data
ans =
'Victorian Doll'
'Train Set'
'Engine Kit'
'Painting Set'
'Space Cruiser'
'Building Blocks'
'Tin Soldier'
'Sail Boat'
'Slinky'
'Teddy Bear'
5-37
5 Using Database Toolbox™ Functions
• Create custom methods that operate on Database Toolbox objects and store
them in the MATLAB workspace.
5-38
Using the exec Function
setdbprefs('Errorhandling','report');
curs = exec(conn,'select * invalidtablename')
setdbprefs('Errorhandling','store');
5-39
5 Using Database Toolbox™ Functions
• After opening a cursor, use fetch to import data from the cursor. Use
resultset, rsmd, and access the Statement property to get properties of
the cursor.
• You can have multiple cursors open at one time.
• A cursor stays open until you close it using the close function.
Database Considerations
• The order of records in your database is not constant. Use values in column
names to identify records. Use the SQL ORDER BY command to sort records.
• Before you modify database tables, ensure that the database is not open
for editing. If you try to edit the database while it is open, you receive
this MATLAB error:
• You might experience issues with text field formats in the Microsoft SQL
Server database management system. Workarounds for these issues are as
follows:
- Convert fields of format NVARCHAR, TEXT, NTEXT, and VARCHAR to CHAR
in the database.
- Use sqlquery to convert data to VARCHAR. For example, run a sqlquery
statement of the form 'select convert(varchar(20),field1) from
table1'.
5-40
Using the exec Function
• Some databases require that you include a symbol, such as #, before and
after a date in a query as follows:
• Some databases require that you include a symbol, such as #, before and
after a date in a query as follows:
5-41
5 Using Database Toolbox™ Functions
fetch Workflow
The fetch function runs the appropriate processes to retrieve data depending
on what object you provide to it as an input argument. This function works
with cursor objects and database connection objects for JDBC/ODBC bridge
and JDBC interfaces. This function works with cursor objects only for the
native ODBC interface.
For the JDBC database driver, use the database function to establish a
database connection.
conn = database(...)
Then, fetch runs when you pass a cursor object, curs, to retrieve as an
argument.
curs = exec(conn,sqlquery)
curs = fetch(curs)
The fetch function runs when you pass a database object, conn, to retrieve
as an argument.
5-42
Using the fetch Function
fetch(conn,sqlquery)
Note You can pass conn as an input argument to fetch when you are using
an JDBC/ODBC bridge or a JDBC interface. For the native ODBC interface,
use curs as the input argument.
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 without
metadata, use fetch with a database connection object as the input argument.
curs = fetch(curs)
After this, you simply need to close this one object. Creating a different
variable for the output cursor object will unnecessarily create two objects
pointing to the same underlying Java statement and result set objects.
5-43
5 Using Database Toolbox™ Functions
curs = fetch(curs)
fetch(curs)
curs2 = fetch(curs)
• The next time fetch is run, records are imported starting with the row
following the specified number of rows in rowlimit. If you specify a row
limit of 0, all the rows of data are fetched.
• Fetching large amounts of data can result in memory or speed issues. Use
rowlimit 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 are
fetched, or until the limited number of rows are fetched, if rowlimit is
specified. Use this method when fetching a large number of rows from
the database.
Database Considerations
• The order of records in your database does not remain constant. Use the
SQL ORDER BY command in your sqlquery statement to sort data.
5-44
Using the fastinsert Function
5-45
5 Using Database Toolbox™ Functions
Database Considerations
• The order of records in your database is not constant. Use values in column
names to identify records.
• If an error message like the following appears when you run fastinsert,
the table might be open in edit mode.
In this case, close the table in the database and rerun the fastinsert
function.
5-46
Using the get Function
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 might need
to extract a single catalog name from 'Catalog' for
functions such as columns, which accept only a single
catalog.
'Driver' Driver used for a JDBC connection, as specified by
database.
'Handle' Identifies a JDBC connection object.
'Instance' Name of the data source for an ODBC connection or the
name of a database for a JDBC connection, as specified
by database.
'Message' Error message returned by database.
'ReadOnly' 1 if the database is read only; 0 if the database is writable.
'TimeOut' Value for LoginTimeout.
5-47
5 Using Database Toolbox™ Functions
Property Value
'TransactionIsolation' Value of the current transaction isolation mode.
'Type' Object type, specifically Database Object.
'URL' For JDBC connections only, the JDBC URL object
jdbc:subprotocol:subname, as specified by database.
'UserName' User name required to connect to a given database, as
specified by database.
'Warnings' Warnings returned by database.
You cannot use the get function to retrieve the password property.
Cursor Objects
Allowable property names and returned values for cursor objects appear in
the following table.
Property Value
'Attributes' Cursor attributes. This field is always empty.
Use the attr function to retrieve cursor
attributes.
'Data' Data in the cursor object data element (the
query results).
'DatabaseObject' Information about a given database object.
'RowLimit' Maximum number of rows returned by fetch,
as specified by set.
'SQLQuery' SQL statement for a cursor, as specified by
exec.
'Message' Error message returned from exec or fetch.
'Type' Object type, specifically Database Cursor
Object.
'ResultSet' Resultset object identifier.
'Cursor' Cursor object identifier.
5-48
Using the get Function
Property Value
'Statement' Statement object identifier.
Driver Objects
Allowable property names and examples of values for driver objects appear
in the following table.
5-49
5 Using Database Toolbox™ Functions
Drivermanager Objects
Allowable property names and examples of values for drivermanager objects
appear in the following table.
Resultset Objects
Allowable property names and examples of values for resultset objects appear
in the following table.
5-50
Using the get Function
The empty strings for CatalogName and TableName indicate that databases
do not return these values.
5-51
5 Using Database Toolbox™ Functions
Allowable Properties
DataReturnFormat and ErrorHandling Properties and Values for setdbprefs
5-52
Using the setdbprefs Function
5-53
5 Using Database Toolbox™ Functions
Allowable
Property Values Description
'JDBCDataSourceFile' Input value, Path to MAT-file containing JDBC data
for example, sources.
'D:/file.mat'
'UseRegistryForSources' 'yes' (default) When set to yes, VQB searches the
or 'no' Microsoft Windows registry for ODBC
data sources that are not uncovered in the
system ODBC.INI file. This message might
appear: Registry editing has been
disabled by your administrator. You
can ignore this harmless message.
5-54
Using the setdbprefs Function
Allowable
Property Values Description
'TempDirForRegistryOutput' Input value, Folder where VQB writes ODBC registry
for example, settings when you run getdatasources.
'D:/work' Use when you add data sources and do not
have write access to the MATLAB Current
Folder. The default is the Windows
temporary folder, which is returned by
the command getenv('temp')). If you
specify a folder to which you do not have
write access or which does not exist, this
error appears:
Cannot export
<folder-name>\ODBC.INI:
Error opening the file.
There may be a disk
or file system error.
'DefaultRowPreFetch' Input numeric Number of rows fetched from the Database
value, default server at a time for any query. The higher
value is '10000' the number, the fewer the number of trips
to the server.
5-55
5 Using Database Toolbox™ Functions
Allowable
Property Values Description
'FetchInBatches' 'yes' or 'no' Automates fetching in batches for large
(default) data sets where you might run into
Java heap memory errors in MATLAB.
When the value is 'yes', fetch and
runsqlscript import the data in batches
in size of 'FetchBatchSize'. For an
example, see fetch.
'FetchBatchSize' Input numeric Automates fetching in batches for
value, default large data sets when used with
value is '1000'. 'FetchInBatches'. When the value of
Supported values 'FetchInBatches' is 'yes', fetch and
are 1000 through runsqlscript import the data in batches
1000000. in size of 'FetchBatchSize'.
For an example, see fetch. For details
about estimating a 'FetchBatchSize'
value, see “Preference Settings for Large
Data Import” on page 4-19.
5-56
6
Functions — Alphabetical
List
attr
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 data
types; an empty value is returned for strings.
scale Precision value for real and numeric data
types; 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.
6-2
attr
ans =
fieldName: 'Age'
typeName: 'LONG'
typeValue: 4
columnWidth: 11
precision: []
scale: []
currency: 'false'
readOnly: 'false'
nullable: 'true'
Message: []
attributes = attr(curs)
attributes(4)
ans =
fieldName: 'Age'
typeName: 'LONG'
typeValue: 4
columnWidth: 11
precision: []
scale: []
currency: 'false'
readOnly: 'false'
nullable: 'true'
Message: []
See Also cols | columnnames | columns | fetch | dmd | get | tables | width
6-3
bestrowid
Syntax b = bestrowid(dbmeta,'cata','sch')
b = bestrowid(dbmeta,'cata','sch','tab')
The result indicates that each entry in the build_id column is unique
and identifies the row.
6-4
clearwarnings
Syntax clearwarnings(conn)
clearwarnings(rset)
help database/clearwarnings
help resultset/clearwarnings
6-5
close
Syntax close(object)
Object Description
conn Database connection object or native ODBC
database connection object
curs Cursor object or native ODBC cursor object
rset Resultset object
Note The MATLAB session closes open cursors and connections when
exiting, however, the database might not free up the cursors and
connections.
6-6
close
Using the native ODBC interface, connect to the database with the
ODBC data source name dbtoolboxdemo with the user name admin
and password admin.
conn = database.ODBCConnection('dbtoolboxdemo','admin','admin');
close(conn);
Using the native ODBC interface, connect to the database with the
ODBC data source name dbtoolboxdemo with the user name admin
and password admin.
conn = database.ODBCConnection('dbtoolboxdemo','admin','admin');
Close the cursor object curs before closing the database connection.
close(curs);
close(conn);
conn = database('dbtoolboxdemo','admin','admin');
6-7
close
Select data from productTable that you access using the database
connection object conn. Assign the returned cursor object to the variable
curs.
rset = resultset(curs);
close(rset);
Close the cursor object curs before closing the database connection.
close(curs);
close(conn);
6-8
cols
numcols = cols(curs)
numcols =
3
6-9
columnnames
Examples 1 Run a SQL query to return all columns from the Microsoft Access
dbtoolboxdemo data source database suppliers table:
fieldString = columnnames(cursor)
fieldString =
'SupplierNumber','SupplierName','City','Country','FaxNumber'
6-10
columnprivileges
Syntax lp = columnprivileges(dbmeta,'cata','sch','tab')
lp = columnprivileges(dbmeta,'cata','sch','tab','l')
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}
lp{1,3}
ans =
'INSERT' 'REFERENCES' 'SELECT' 'UPDATE'
6-11
columns
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 cell
arrays containing the column names in each table.
l{1,2}
ans =
'ENAME' 'JOB' 'SAL' 'COMM'
6-12
commit
Syntax commit(conn)
get(conn,'AutoCommit')
ans =
off
1 Insert exdata into the columns DEPTNO, DNAME, and LOC in the table
DEPT, for the data source conn.
commit(conn)
6-13
confds
Alternatives Select Define JDBC data sources from the Visual Query Builder
Query menu.
Syntax confds
Description confds displays the VQB Define JDBC data sources dialog box. Use
confds only to build and run queries using Visual Query Builder with
JDBC drivers.
For information about how to use the Define JDBC data sources dialog
box to configure JDBC drivers, see “Configuring a Driver and Data
Source” on page 2-13.
6-14
confds
6-15
crossreference
Examples Run crossreference to get primary and foreign key information. The
database metadata object is dbmeta, the primary and foreign catalog is
orcl, the primary and foreign schema is SCOTT, the table that contains
the referenced primary key is DEPT, and the table that contains the
foreign 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.
6-16
crossreference
There is only one foreign key in the schema SCOTT. The table DEPT
contains a primary key DEPTNO that is referenced by the field DEPTNO in
the 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 the
getCrossReference property on the Oracle Java Web site:
http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.htm
6-17
crossreference
6-18
cursor.fetch
Purpose Import data into MATLAB Workspace from cursor object created by
exec
6-19
cursor.fetch
Tips • This page documents fetch for a cursor object. For details about
using fetch, cursor.fetch, and database.fetch, see fetch.
Unless otherwise noted, fetch in this documentation refers to
cursor.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 the
dbtoolboxdemo data source.
conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')
conn =
Instance: 'dbtoolboxdemo'
UserName: 'admin'
Message: []
Handle: [1x1 database.internal.ODBCConnectHandle]
TimeOut: 0
AutoCommit: 0
Type: 'ODBCConnection Object'
6-20
cursor.fetch
curs =
curs.Data
ans =
'Victorian Doll'
'Train Set'
'Engine Kit'
'Painting Set'
'Space Cruiser'
'Building Blocks'
'Tin Soldier'
'Sail Boat'
'Slinky'
'Teddy Bear'
close(curs);
6-21
cursor.fetch
Working with the dbtoolboxdemo data source, use exec to select data
in column City, for example, in table suppliers. Then, use fetch to
import all data from the SQL statement into the cursor object curs,
and store the data in a cell array contained in the cursor object field
curs.Data.
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]
curs.Data
ans =
'New York'
'London'
'Adelaide'
'Dublin'
'Boston'
'New York'
'Wellesley'
6-22
cursor.fetch
'Nashua'
'London'
'Belfast'
close(curs);
Import a Specified Number of Rows
curs =
Attributes: []
Data: {3x1 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]
curs.Data
ans =
'Victorian Doll'
'Train Set'
'Engine Kit'
6-23
cursor.fetch
Rerun the fetch function to return the second three rows of data.
curs = fetch(curs,3);
curs.Data
ans =
'Painting Set'
'Space Cruiser'
'Building Blocks'
close(curs);
rowLimit =
6-24
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(curs);
6-25
cursor.fetch
ans =
13
5
16
close(curs);
A =
[ 2101] [0]
[ 3546] [1]
[33116] [1]
[34155] [0]
[34267] [1]
6-26
cursor.fetch
class(A{1,2})
ans =
logical
close(curs);
setdbprefs('FetchInBatches','yes');
setdbprefs('FetchBatchSize','2');
conn = database('dbtoolboxdemo','','');
curs = exec(conn,'select * from productTable');
curs = fetch(curs);
A = curs.Data
A =
6-27
cursor.fetch
You can exercise a row limit on the final output even when the
FetchInBatches setting is 'yes'.
setdbprefs('FetchInBatches','yes');
setdbprefs('FetchBatchSize','2');
curs = exec(conn,'select * from productTable');
curs = fetch(curs,3);
A = curs.Data
A =
close(curs);
6-28
cursor.fetch
6-29
database
conn =
database(instance,username,password,driver,databaseurl)
conn = database(instance,username,password,Name,Value)
conn = database.ODBCConnection(instance,username,password)
returns a database connection object for the connection to the ODBC
data source setup instance using a native ODBC interface.
conn =
database(instance,username,password,driver,databaseurl)
connects to the database instance using a JDBC driver.
conn = database(instance,username,password,Name,Value)
connects to the database instance using a JDBC driver with connection
properties specified by one or more Name,Value pair arguments.
6-30
database
example, instance might be the SID or the service name when you are
connecting to an Oracle database or instance might be the catalog
name when you are connecting to a MySQL database. For details about
your database name, contact your database administrator or refer to
your database documentation.
password - Password
string
Password required to access the database, specified as a string. If no
password is required, specify empty strings, ''.
6-31
database
6-32
database
’AuthType’ - Authentication
'Server' (default) | 'Windows'
Authentication type (valid only for Microsoft SQL Server), specified
as the comma-separated pair consisting of 'AuthType' and one of the
following strings:
• 'Server'
• 'Windows'
Specify 'Windows' for Windows Authentication.
Example: 'AuthType','Windows'
6-33
database
Property Description
Instance Data source name when using ODBC or
database name when using JDBC
UserName User name used for database login
Driver JDBC or JDBC/ODBC driver object used for
database connection
URL Driver vendor specific string for database
connection
Constructor Internal Java or C++ representation of database
connection object
Message Database connection status message that
is empty when a successful connection is
established
Handle Internal Java or C++ representation of database
connection object
TimeOut Number of seconds that the driver waits while
trying to establish a database connection before
throwing an error
AutoCommit Set to on if you want updates to be applied to
the database automatically and set to off when
you want updates to be explicitly committed to
the database
Type Database connection object or
database.ODBCConnection object
6-34
database
Instance property contains the data source name, and, for JDBC, the
Instance property contains the database name.
Tips • Use logintimeout before database to set the maximum time for a
connection attempt.
• Alternatively use Database Explorer to connect to databases.
• When making a JDBC connection using name-value connection
properties:
- You can skip the Server parameter when connecting to a database
locally.
- You can skip the PortNumber parameter when connecting to a
database server listening on the default port (except for Oracle
connections).
conn = database.ODBCConnection('dbtoolboxdemo','username','pwd')
conn =
Instance: 'dbtoolboxdemo'
UserName: 'username'
Message: []
Handle: [1x1 database.internal.ODBCConnectHandle]
TimeOut: 0
AutoCommit: 0
Type: 'ODBCConnection Object'
6-35
database
close(conn);
ODBC Connection
Connect to the dbtoolboxdemo database using the JDBC/ODBC bridge.
conn = database('dbtoolboxdemo','username','pwd')
conn =
Instance: 'dbtoolboxdemo'
UserName: 'username'
Driver: []
URL: []
Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
Message: []
Handle: [1x1 sun.jdbc.odbc.JdbcOdbcConnection]
TimeOut: 0
AutoCommit: 'on'
Type: 'Database Object'
close(conn);
6-36
database
conn =
Instance: 'test_db'
UserName: ''
Driver: []
URL: []
Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
Message: []
Handle: [1x1 com.microsoft.sqlserver.jdbc.SQLServerConnection
TimeOut: 0
AutoCommit: 'on'
Type: 'Database Object'
close(conn);
6-37
database
conn = database('dbname','username','pwd',...
'com.sybase.jdbc4.jdbc.SybDriver','URL')
conn =
Instance: 'dbname'
UserName: 'username'
Driver: 'com.sybase.jdbc4.jdbc.SybDriver'
URL: 'URL'
Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
Message: []
Handle: [1x1 com.sybase.jdbc4.jdbc.SybConnection]
TimeOut: 0
AutoCommit: 'on'
Type: 'Database Object'
close(conn);
Connect to the database test_db using the user name username and
password pwd. Enter the driver type as thin for a default connection
to Oracle. To connect to Oracle with Windows authentication use oci.
6-38
database
The database server machine name is remotehost and the port number
that the server is listening on is 1234. For details, see “Oracle JDBC
for Windows” on page 2-51.
conn = database('test_db','username','pwd','Vendor','Oracle',...
'DriverType','thin','Server','remotehost','PortNumber',1234)
conn =
Instance: 'test_db'
UserName: 'username'
Driver: []
URL: []
Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
Message: []
Handle: [1x1 oracle.jdbc.driver.T4CConnection]
TimeOut: 0
AutoCommit: 'on'
Type: 'Database Object'
close(conn);
conn = database('test_db','username','pwd','Vendor','MySQL',...
'Server','remotehost')
6-39
database
conn =
Instance: 'test_db'
UserName: 'username'
Driver: []
URL: []
Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
Message: []
Handle: [1x1 com.mysql.jdbc.JDBC4Connection]
TimeOut: 0
AutoCommit: 'on'
Type: 'Database Object'
close(conn);
dbpath = ['C:\Data\Matlab\MyDatabase.accdb'];
conn = database('','','','sun.jdbc.odbc.JdbcOdbcDriver',url);
6-40
database
close(conn);
Connect to the database test_db using the user name username and
password pwd on the machine remotehost. For details, see “PostgreSQL
JDBC for Windows” on page 2-79.
conn = database('test_db','username','pwd','Vendor','PostgreSQL',...
'Server','remotehost')
conn =
Instance: 'test_db'
UserName: 'username'
Driver: []
URL: []
Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
Message: []
Handle: [1x1 org.postgresql.jdbc4.Jdbc4Connection]
TimeOut: 0
AutoCommit: 'on'
Type: 'Database Object'
close(conn);
6-41
database
6-42
database
6-43
database.catalogs
Syntax P = catalogs(conn)
6-44
database.columns
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 the
database connection conn.
P = columns(conn,C) returns all columns for all tables of all schemas
for the given catalog C.
P = columns(conn,C,S) returns the columns for all tables for the
given catalog C and schema S.
P = columns(conn,C,S,T) returns the columns for the given database
connection conn, the catalog C, the schema S, and the table T.
6-45
database.fetch
Input conn
Arguments A database connection object.
sqlquery
An SQL statement.
fetchbatchsize
Specifies the number of rows of data to import at a time. Use
fetchbatchsize when importing large amounts of data. Retrieving
data in increments, as specified by fetchbatchsize, helps reduce
overall retrieval time. If fetchbatchsize is not provided, a default
value of FetchBatchSize is used. FetchBatchSize is set using
setdbprefs.
Output results
Arguments A cell array, table, dataset, structure, or numeric matrix depending on
specifications set by setdbprefs.
Tips • You call the database.fetch function with fetch rather than
database.fetch. You implicitly call database.fetch by passing a
database object, conn, to fetch. The fetch function also works with
a cursor object. See cursor.fetch.
6-46
database.fetch
• The order of records in your database does not remain constant. Use
the SQL ORDER BY command in your sqlquery statement to sort data.
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
6-47
database.fetch
Import the InvoiceNumber and Paid columns from the Invoice table
in the dbtoolboxdemo database.
conn = database('dbtoolboxdemo','','');
setdbprefs('DataReturnFormat','cellarray')
results = fetch(conn,['select InvoiceNumber, '...
'Paid from Invoice']);
View the size of the cell array into which the results were returned.
size(results)
ans =
12 2
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
6-48
database.fetch
6-49
database.schemas
Syntax P = schemas(conn)
6-50
database.tables
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 database
connection object conn.
T = tables(conn,C) returns all tables and table types for all schemas
of the given catalog name C.
T = tables(conn,C,S) returns the list of tables and table types for the
database with the catalog name C and schema name S.
6-51
datainsert
Syntax datainsert(conn,tablename,columnnames,data)
6-52
datainsert
Data Types
cell
Establish the connection conn to a MySQL database with the user name
username and password pwd.
conn = database('MySQL','username','pwd');
ans =
[ 1] [1700] [14.5000]
6-53
datainsert
[ 2] [1200] [ 9.3000]
[ 3] [ 356] [17.2000]
[ 4] [2580] [21.4000]
[ 5] [9000] [ 3.0500]
[ 6] [4540] [ 8.1000]
[ 7] [6034] [16.2000]
[ 8] [8350] [ 5.1000]
[ 9] [2339] [13.2000]
[ 10] [ 723] [24.3000]
[ 11] [ 567] [11.2000]
[ 12] [1278] [22.3000]
[ 13] [1700] [16.8000]
[ 14] [2000] [19.1000]
[ 15] [1200] [20.3000]
[7777] [ 100] [ 50]
[7777] [ 100] [ 50]
[8888] [ 200] [ 101]
columnnames = {'productNumber','Quantity','Price'};
Insert the input data into the table inventoryTable using database
connection conn.
tablename = 'inventoryTable';
datainsert(conn,tablename,columnnames,data);
6-54
datainsert
ans =
[ 1] [1700] [14.5000]
[ 2] [1200] [ 9.3000]
[ 3] [ 356] [17.2000]
[ 4] [2580] [21.4000]
[ 5] [9000] [ 3.0500]
[ 6] [4540] [ 8.1000]
[ 7] [6034] [16.2000]
[ 8] [8350] [ 5.1000]
[ 9] [2339] [13.2000]
[ 10] [ 723] [24.3000]
[ 11] [ 567] [11.2000]
[ 12] [1278] [22.3000]
[ 13] [1700] [16.8000]
[ 14] [2000] [19.1000]
[ 15] [1200] [20.3000]
[7777] [ 100] [ 50]
[7777] [ 100] [ 50]
[8888] [ 200] [ 101]
[ 50] [ 100] [15.5000]
close(conn);
conn = database('MySQL','username','pwd');
6-55
datainsert
curs.Data
ans =
[ 1] [1700] [14.5000]
[ 2] [1200] [ 9.3000]
[ 3] [ 356] [17.2000]
[ 4] [2580] [21.4000]
[ 5] [9000] [ 3.0500]
[ 6] [4540] [ 8.1000]
[ 7] [6034] [16.2000]
[ 8] [8350] [ 5.1000]
[ 9] [2339] [13.2000]
[ 10] [ 723] [24.3000]
[ 11] [ 567] [11.2000]
[ 12] [1278] [22.3000]
[ 13] [1700] [16.8000]
[ 14] [2000] [19.1000]
[ 15] [1200] [20.3000]
[7777] [ 100] [ 50]
[7777] [ 100] [ 50]
[8888] [ 200] [ 101]
[ 50] [ 100] [15.5000]
columnnames = {'productNumber','Quantity','Price'};
Insert the input data into the table inventoryTable using database
connection conn.
tablename = 'inventoryTable';
datainsert(conn,tablename,columnnames,data);
6-56
datainsert
ans =
[ 1] [1700] [14.5000]
[ 2] [1200] [ 9.3000]
[ 3] [ 356] [17.2000]
[ 4] [2580] [21.4000]
[ 5] [9000] [ 3.0500]
[ 6] [4540] [ 8.1000]
[ 7] [6034] [16.2000]
[ 8] [8350] [ 5.1000]
[ 9] [2339] [13.2000]
[ 10] [ 723] [24.3000]
[ 11] [ 567] [11.2000]
[ 12] [1278] [22.3000]
[ 13] [1700] [16.8000]
[ 14] [2000] [19.1000]
[ 15] [1200] [20.3000]
[7777] [ 100] [ 50]
[7777] [ 100] [ 50]
[8888] [ 200] [ 101]
[ 50] [ 100] [15.5000]
[ 55] [ 200] [20.5000]
close(conn);
6-57
dexplore
Syntax dexplore
Examples For details about Database Explorer, after starting Database Explorer,
click Help on the Database Explorer Toolstrip:
6-58
dmd
help dmd/Contents
Examples Create a database metadata object dbmeta for the database connection
conn and list its properties:
dbmeta = dmd(conn);
v = get(dbmeta)
6-59
driver
Syntax d = driver('s')
6-60
drivermanager
Syntax dm = drivermanager
dm = drivermanager
get(dm)
6-61
exec
6-62
exec
Property Description
Attributes Not used.
Data Contains the resulting data after executing
fetch.
DatabaseObject Database connection object or
database.ODBCConnection object that
opened the cursor object.
RowLimit Number of rows to fetch at a time.
SQLQuery SQL statement to execute.
Message Contains the error messages generated from
executing the SQL statement. If this property
is empty, then the SQL statement executed
successfully.
Type Database cursor object or database.ODBCCursor
object 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 these
properties from the previous list: Data, RowLimit, SQLQuery, Message,
Type, and Statement.
Examples Select Data from a Database Table Using the Native ODBC
Interface
Create a connection conn using the native ODBC interface and the
dbtoolboxdemo data source.
6-63
exec
conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')
conn =
Instance: 'dbtoolboxdemo'
UserName: 'admin'
Message: []
Handle: [1x1 database.internal.ODBCConnectHandle]
TimeOut: 0
AutoCommit: 0
Type: 'ODBCConnection Object'
curs =
Data: 0
RowLimit: 0
SQLQuery: 'select * from productTable'
Message: []
Type: 'ODBCCursor Object'
Statement: [1x1 database.internal.ODBCStatementHandle]
6-64
exec
After you finish with the cursor object, close the cursor.
close(curs);
Using the dbtoolboxdemo data source, select data from the suppliers
table that you access using the database connection, conn. Assign the
returned cursor object to the variable curs.
curs =
Attributes: []
Data: 0
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: 0
After you finish with the cursor object, close the cursor.
close(curs);
6-65
exec
exec tries to execute the SQL statement. Assign the returned cursor
object to the variable curs.
curs =
Attributes: []
Data: 0
DatabaseObject: [1x1 database]
RowLimit: 0
SQLQuery: '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);
After you are finished with the cursor object, close the cursor.
close(curs);
6-66
exec
Train Set
To perform the query using your input, run the following code.
ans =
6-67
exec
ans =
After you are finished with the cursor object, close the cursor.
close(curs);
sqlquery = 'rollback';
exec(conn,sqlquery);
curs = ans;
close(curs);
sqlquery = 'commit';
exec(conn,sqlquery);
6-68
exec
After you are finished with the cursor object, close the cursor.
curs = ans;
close(curs);
After you are finished with the cursor object, close the cursor.
close(curs);
exec(conn,sqlquery);
Use the SQL ALTER command to add a new column, City, to the table.
After you are finished with the cursor object, close the cursor.
close(curs);
6-69
exec
For Microsoft SQL Server, the statement 'SET NOCOUNT ON' suppresses
the results of insert, update or any non-select statements that might
be before the final select query so you can fetch the results of the select
query.
Use exec when the stored procedure returns one or more result sets. For
procedures that return output parameters, use runstoredprocedure.
conn = database('test_db','root','matlab',...
'Vendor','Microsoft SQL Server',...
'Server','servername','PortNumber',1234)
conn =
6-70
exec
Instance: 'test_db'
UserName: 'root'
Driver: []
URL: []
Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
Message: []
Handle: [1x1 com.microsoft.sqlserver.jdbc.SQLServerConnection
TimeOut: 0
AutoCommit: 'on'
Type: 'Database Object'
setdbprefs('DataReturnFormat','table');
curs =
Attributes: []
Data: 0
DatabaseObject: [1x1 database]
RowLimit: 0
SQLQuery: '{call getSupplierInfo('New York')}'
Message: []
Type: 'Database Cursor Object'
ResultSet: [1x1 com.microsoft.sqlserver.jdbc.SQLServerResultS
6-71
exec
curs = fetch(curs)
curs =
Attributes: []
Data: [3x5 table]
DatabaseObject: [1x1 database]
RowLimit: 0
SQLQuery: '{call getSupplierInfo('New York')}'
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]
curs contains the supplier data from running the stored procedure,
getSupplierInfo, in table format.
curs.Data
ans =
6-72
exec
Country FaxNumber
--------------- --------------
'United States' '212 435 1617'
'United States' '212 435 1618'
'USA' '14678923104'
>>
Close the Database Cursor Object, curs, and then close the
connection Database Object, conn.
close(curs);
close(conn);
6-73
exec
After you are finished with the cursor object, close the cursor.
close(curs);
6-74
exportedkeys
Examples Get foreign exported key information for the schema SCOTT for the
database 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'
6-75
exportedkeys
In the schema SCOTT, only one primary key is exported to (referenced by)
another table. DEPTNO, the primary key of the table DEPT, is referenced
by the field DEPTNO in the table EMP. The referenced table is DEPT and
the referencing table is EMP. In the DEPT table, DEPTNO is an exported
key. Reciprocally, the DEPTNO field in the table EMP is an imported key.
For a description of codes for update and delete rules, see the
getExportedKeys property on the Oracle Java Web site:
http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html.
6-76
fastinsert
Syntax fastinsert(conn,tablename,colnames,exdata)
6-77
fastinsert
Data Types
cell
Create a connection conn using the native ODBC interface and the
dbtoolboxdemo data source.
conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')
conn =
Instance: 'dbtoolboxdemo'
UserName: 'admin'
Message: []
Handle: [1x1 database.internal.ODBCConnectHandle]
TimeOut: 0
AutoCommit: 0
Type: 'ODBCConnection Object'
6-78
fastinsert
ans =
tablename = 'productTable';
colnames = {'productNumber' 'stockNumber' 'supplierNumber' ...
'unitCost' 'productDescription'};
Store the data for the insert in a cell array, exdata. The data
contains productNumber equal to 11, stockNumber equal to 500565,
supplierNumber equal to 1010, unitCost equal to $20, and
productDescription equal to 'Cooking Set'. Then, convert the cell
array to a table, exdata_table.
exdata_table =
6-79
fastinsert
fastinsert(conn,tablename,colnames,exdata_table);
ans =
close(conn);
Insert a Record
6-80
fastinsert
Assign the data to the cell array exdata. The data for insertion is
productNumber equals 7777, Quantity equals 100, and Price equals
50.00.
exdata = {7777,100,50.00};
tablename = 'inventoryTable';
colnames = {'productNumber','Quantity','Price'};
fastinsert(conn,tablename,colnames,exdata);
close(conn);
tablename = 'inventoryTable';
colnames = {'productNumber','Quantity','Price'};
6-81
fastinsert
fastinsert(conn,tablename,colnames,exdata);
For details, there are three sample files for different database vendors
that demonstrate bulk insert:
• matlabroot/toolbox/database/dbdemos/mssqlserverbulkinsert.m
• matlabroot/toolbox/database/dbdemos/mysqlbulkinsert.m
• matlabroot/toolbox/database/dbdemos/oraclebulkinsert.m
close(conn);
Import Records, Perform Calculations, and Export Data
This example shows how to retrieve sales data from a salesVolume
table, calculate the sum of sales for 1 month, store this data in a cell
array, and export this data to a yearlySales table.
conn = database('dbtoolboxdemo','admin','admin');
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
setdbprefs('DataReturnFormat','numeric');
Import 10 rows of data from the March column in the salesVolume table.
AA = curs.Data
AA =
6-82
fastinsert
981
1414
890
1800
2600
2800
800
1500
1000
821
Calculate the sum of the March sales and assign the result to the
variable sumA.
sumA = sum(AA(:))
sumA =
14606
exdata(1,1) = {'March'}
exdata =
'March'
exdata(1,2) = {sumA}
exdata =
'March' [14606]
6-83
fastinsert
tablename = 'yearlySales';
colnames = {'Month','salesTotal'};
Use the get function to determine the current status of the AutoCommit
database flag. This status determines whether the exported data is
automatically committed to the database. If the flag is off, you can
undo an update; if it is on, data is automatically committed to the
database.
get(conn,'AutoCommit')
ans =
on
fastinsert(conn,tablename,colnames,exdata);
close(curs);
close(conn);
6-84
fastinsert
exdata = [25,439,60.00];
tablename = 'inventoryTable';
colnames = {'productNumber','Quantity','Price'};
fastinsert(conn,tablename,colnames,exdata);
close(conn);
set(conn,'AutoCommit','off');
Insert the cell array exdata into the inventoryTable with column
names colnames.
exdata = {157,358,740.00};
colnames = {'productNumber','Quantity','Price'};
tablename = 'inventoryTable';
fastinsert(conn,tablename,colnames,exdata);
commit(conn);
curs = exec(conn,'commit');
6-85
fastinsert
close(conn);
conn = database('dbtoolboxdemo','admin','admin');
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
exdata.InvoiceNumber{1} = 2101;
exdata.Paid{1} = logical(1);
Insert the paid invoice data into the invoice table with column names
colnames.
colnames = {'InvoiceNumber';'Paid'};
tablename = 'invoice';
fastinsert(conn,tablename,colnames,exdata);
View the new record in the database to verify that the Paid field is
BOOLEAN. In some databases, the MATLAB logical value 0 is shown as
a BOOLEAN false, No, or a cleared check box.
close(conn);
See Also commit | database | exec | insert | logical | rollback | set | get
| update | querybuilder
6-86
fastinsert
6-87
fetch
Purpose Import data into MATLAB workspace from cursor object or from
execution of SQL statement
results = fetch(conn,sqlquery)
results = fetch(conn,sqlquery,fetchbatchsize)
Description curs = fetch(curs) imports all rows of data into the cursor object
curs from the open SQL cursor object curs.
6-88
fetch
SQL string
SQL statement, specified as an SQL string to execute.
Data Types
char
6-89
fetch
Examples Import All Rows of Data with the Native ODBC Interface
Using the Cursor Object
Create a connection conn using the native ODBC interface and the
dbtoolboxdemo data source.
conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')
conn =
Instance: 'dbtoolboxdemo'
UserName: 'admin'
Message: []
Handle: [1x1 database.internal.ODBCConnectHandle]
TimeOut: 0
AutoCommit: 0
Type: 'ODBCConnection Object'
Working with the dbtoolboxdemo data source, use fetch to import all
data into the database.ODBCCursor object, curs, and store the data in
a cell array contained in the cursor object field curs.Data.
curs =
6-90
fetch
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);
Working with the dbtoolboxdemo data source, use exec to select data
in column City, for example, in table suppliers. Then, use fetch to
import all data from the SQL statement into the cursor object curs,
and store the data in a cell array contained in the cursor object field
curs.Data.
curs =
6-91
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]
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);
6-92
fetch
curs =
Attributes: []
Data: {3x1 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]
curs.Data
ans =
'Victorian Doll'
'Train Set'
'Engine Kit'
Rerun the fetch function to return the second three rows of data.
curs.Data
ans =
'Painting Set'
6-93
fetch
'Space Cruiser'
'Building Blocks'
After you are finished with the cursor object, close the cursor object.
close(curs);
rowlimit =
ans =
'Victorian Doll'
'Train Set'
ans =
'Engine Kit'
6-94
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);
6-95
fetch
ans =
13
5
16
After you are finished with the cursor object, close the cursor object.
close(curs);
A =
[ 2101] [0]
[ 3546] [1]
[33116] [1]
[34155] [0]
[34267] [1]
class(A{1,2})
ans =
logical
After you are finished with the cursor object, close the cursor object.
close(curs);
6-96
fetch
setdbprefs('FetchInBatches', 'yes');
setdbprefs('FetchBatchSize', '2');
conn = database('dbtoolboxdemo', '', '');
curs = exec(conn, 'select * from productTable');
curs = fetch(curs);
A = curs.Data
A =
6-97
fetch
You can exercise a row limit on the final output even when the
FetchInBatches setting is 'yes'.
setdbprefs('FetchInBatches', 'yes');
setdbprefs('FetchBatchSize', '2');
curs = exec(conn, 'select * from productTable');
curs = fetch(curs, 3);
A = curs.Data
A =
In this case, fetch retrieves the first three rows of productTable, two
rows at a time.
After you are finished with the cursor object, close the cursor object.
close(curs);
Using the dbtoolboxdemo data source that you access using the
database connection object, conn, import the productDescription
column from productTable. Set the data return format to 'cellarray'
using setdbprefs.
6-98
fetch
setdbprefs('DataReturnFormat','cellarray');
sqlquery = 'select productdescription from productTable';
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
Using the dbtoolboxdemo data source that you access using the
database connection object, conn, import the productDescription
column from the productTable by using the fetchbatchsize argument.
setdbprefs('DataReturnFormat','cellarray');
6-99
fetch
results = fetch(conn,sqlquery,fetchbatchsize);
Using the dbtoolboxdemo data source that you access using the
database connection object, conn, import the InvoiceNumber and
Paid columns from the Invoice table. Set the data return format to
'cellarray' using setdbprefs.
setdbprefs('DataReturnFormat','cellarray');
sqlquery = 'select InvoiceNumber, Paid from Invoice';
View the size of the cell array into which the results were returned.
size(results)
ans =
12 2
results(1,:)
ans =
6-100
fetch
[2101] [0]
View the data type of the second element in the first row of data.
class(results{1,2})
ans =
logical
6-101
fetchmulti
Description curs = fetchmulti(curs) imports data from the open SQL cursor
object curs into the object curs, where the open SQL cursor object
contains multiple resultsets.
Multiple resultsets are retrieved via exec with a sqlquery statement
that runs a stored procedure consisting of two select statements.
cursmulti.Data contains data from each resultset associated with
cursmulti.Statement. cursmulti.Data is a cell array consisting of cell
arrays, structures, or numeric matrices as specified in setdbprefs; the
data type is the same for all resultsets.
Examples Use exec to run a stored procedure that includes multiple select
statements 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: 0
SQLQuery: '{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]
6-102
fetchmulti
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
6-103
get
Syntax s = get(object)
v = get(object,property)
6-104
get
conn = database('MySQL','username','pwd');
dbmeta = dmd(conn);
v = get(dbmeta)
v =
AllProceduresAreCallable: 1
AllTablesAreSelectable: 1
DataDefinitionCausesTransactionCommit: 1
DataDefinitionIgnoredInTransactions: 0
DoesMaxRowSizeIncludeBlobs: 0
Catalogs: {8x1 cell}
6-105
get
CatalogSeparator: '.'
CatalogTerm: 'DATABASE'
DatabaseProductName: 'ACCESS'
DatabaseProductVersion: '04.00.0000'
DefaultTransactionIsolation: 2
DriverMajorVersion: 2
DriverMinorVersion: 1
DriverName: 'JDBC-ODBC Bridge (ACEODBC.DLL
DriverVersion: '2.0001 (Microsoft Access data
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: '\'
6-106
get
v.Catalogs
ans =
'D:\matlab\toolbox\database\dbdemos\db1'
'D:\matlab\toolbox\database\dbdemos\origtutorial'
'D:\matlab\toolbox\database\dbdemos\tutorial'
'D:\matlab\toolbox\database\dbdemos\tutorial1'
close(conn);
6-107
get
conn = database('MySQL','username','pwd');
v = get(conn,'AutoCommit')
v =
on
close(conn);
6-108
getdatasources
Syntax d = getdatasources
Description d = getdatasources returns the names of valid ODBC and JDBC data
sources on the system as a cell array d of strings. The function gets
the names of ODBC data sources from the ODBC.INI file located in the
folder returned by running:
myODBCdir = getenv('WINDIR')
d is empty when the ODBC.INI file is valid, but no data sources are
defined. d equals -1 when the ODBC.INI file cannot be opened.
The function also retrieves the names of data sources that are in the
system registry but not in the ODBC.INI file.
If you do not have write access to myODBCdir, the results of
getdatasources may not include data sources that you recently
added. In this case, specify a temporary, writable, output folder via
the preference TempDirForRegistryOutput. For details about this
preference, see setdbprefs.
getdatasources gets the names of JDBC data sources from the file
that you define using setdbprefs or the Define JDBC data sources
dialog box.
d = getdatasources
d =
'MS Access Database' 'dbtoolboxdemo'
6-109
importedkeys
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'
6-110
importedkeys
In the schema SCOTT, there is only one foreign imported key. The table
EMP contains a field, DEPTNO, that references the primary key in the
DEPT 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, the
DEPTNO field in the table DEPT is an exported foreign key and the
primary key.
For a description of the codes for update and delete rules, see the
getImportedKeys property on the Oracle Java Web site:
http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.htm
6-111
importedkeys
6-112
indexinfo
Examples Get index and statistics information for the table DEPT in the schema
SCOTT 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.
6-113
indexinfo
For details about the index information, see the getIndexInfo property
on the Oracle Java Web site:
http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html.
6-114
insert
Syntax insert(conn,tablename,colnames,exdata)
Description insert(conn,tablename,colnames,exdata)
insert exports records from the MATLAB variable exdata into new
rows 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 column
names for tablename as strings in the MATLAB cell array colnames. If
exdata is a structure, field names in the structure must exactly match
colnames. If exdata is a table or a dataset, the variable names in the
table or dataset must exactly match colnames.
When working with a JDBC driver connection or a JDBC/ODBC bridge
connection established using the database function, fastinsert offers
improved performance over insert. This is because insert creates
and executes an SQL insert query for each row of data. fastinsert
creates the insert query only once and then allows for the data values
to be plugged in. All rows of data get inserted as a batch resulting in
an overall faster performance over insert. However, since fastinsert
relies more on driver functions compared to insert, it is possible in
some edge case scenarios that the driver functions do not work as
expected. In such cases, insert might be preferred, especially if the
data to be inserted is small. datainsert is faster than fastinsert but
needs data to be formatted in a specific way and accepts cell arrays and
numeric matrices as input data.
When working with a native ODBC connection established using the
database.ODBCConnection function, fastinsert and insert are
identical. datainsert is not supported for native ODBC connections.
insert uses the same syntax as fastinsert.
6-115
insert
Notes:
• insert supports the native ODBC interface. To insert dates
and 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 following
special formatting. Each field or variable in a structure, table, or
dataset must be a cell array or double vector of size m*1, where m is
the number of rows to be inserted.
1 Create a connection conn using the native ODBC interface and the
dbtoolboxdemo data source.
conn = database.ODBCConnection('dbtoolboxdemo','admin','admin')
conn =
Instance: 'dbtoolboxdemo'
UserName: 'admin'
Message: []
Handle: [1x1 database.internal.ODBCConnectHandle]
TimeOut: 0
AutoCommit: 0
Type: 'ODBCConnection Object'
6-116
insert
curs = fetch(curs);
curs.Data
ans =
4 Store the data for the insert in a cell array, exdata. The data
contains productNumber equal to 11, stockNumber equal to 400565,
supplierNumber equal to 1010, unitCost equal to $10, and
productDescription equal to 'Rubik''s Cube'. Then, convert the
cell array to a table, exdata_table.
exdata_table =
6-117
insert
tablename = 'productTable';
insert(conn,tablename,colnames,exdata_table);
ans =
1 Using the dbtoolboxdemo data source, select and display the data
from the yearlySales table.
6-118
insert
ans =
3 Store the data for the insert in a cell array, exdata. The data
contains Month equal to 'March', salesTotal equal to $50, and
Revenue equal to $2000.
exdata = {'March',50,2000};
tablename = 'yearlySales';
insert(conn,tablename,colnames,exdata);
ans =
A new row appears in the yearlySales table with the data from
exdata.
6-119
insert
6-120
isconnection
Syntax a = isconnection(conn)
a = isconnection(conn)
a =
1
6-121
isdriver
Syntax a = isdriver(d)
a = isdriver(d)
a =
1
6-122
isjdbc
Syntax a = isjdbc(d)
a = isjdbc(d)
a =
1
6-123
isnullcolumn
Syntax a = isnullcolumn(rset)
1 Run:
curs = fetch(curs,1);
rset = resultset(curs);
isnullcolumn(rset)
ans =
0
curs.Data
ans =
[1400]
1 Run:
curs = fetch(curs,1);
rset = resultset(curs);
isnullcolumn(rset)
ans =
1
6-124
isnullcolumn
curs.Data
ans =
[NaN]
6-125
isreadonly
Syntax a = isreadonly(conn)
a = isreadonly(conn)
The result indicates that the database connection conn is read only:
a =
1
6-126
isurl
Description a = isurl(d, 's') returns 1 if the database URL s for the driver
object d is valid. It returns 0 otherwise.
The URL s is of the form jdbc:odbc:name or name.
a = isurl(d, 'jdbc:odbc:thin:@144.212.123.24:1822:')
a =
1
6-127
logintimeout
Note If you do not specify a value for logintimeout and the MATLAB
session cannot establish a database connection, your MATLAB session
may freeze.
6-128
logintimeout
logintimeout(5)
ans =
5
logintimeout('oracle.jdbc.driver.OracleDriver')
ans =
0
timeout = ...
logintimeout('oracle.jdbc.driver.OracleDriver', 5)
timeout =
5
6-129
logintimeout
logintimeout('oracle.jdbc.driver.OracleDriver')
ans =
5
6-130
namecolumn
Syntax x = namecolumn(rset, n)
Examples 1 Get the indices for the column names DNAME and LOC resultset object
rset.
x = namecolumn(rset, {'DNAME';'LOC'})
x =
2 3
x = namecolumn(rset, 'LOC')
6-131
ping
Syntax ping(conn)
ping(conn)
ans =
DatabaseProductName: 'Oracle'
DatabaseProductVersion: [1x166 char]
JDBCDriverName: 'Oracle JDBC driver'
JDBCDriverVersion: '7.3.4.0.2'
MaxDatabaseConnections: 0
CurrentUserName: 'scott'
DatabaseURL: 'jdbc:oracle:thin: ...
@144.212.123.24:1822:orcl'AutoCommitTransactions:'True'
6-132
ping
ping(conn)
Cannot Ping the Database Connection
6-133
primarykeys
k = primarykeys(dbmeta,'orcl','SCOTT','DEPT')
k =
'orcl' 'SCOTT' 'DEPT' 'DEPTNO' '1' 'PK_DEPT'
6-134
primarykeys
6-135
procedurecolumns
Examples Get stored procedure parameters for the schema ORG, in the catalog
tutorial, 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'
6-136
procedurecolumns
6-137
procedures
Examples Get the names of stored procedures for the catalog DBA for the database
metadata object dbmeta:
p = procedures(dbmeta,'DBA')
p =
'sp_contacts'
'sp_customer_list'
'sp_customer_products'
'sp_product_info'
'sp_retrieve_contacts'
'sp_sales_order'
curs = exec(conn,'sp_customer_list');
curs = fetch(conn)
curs =
Attributes: []
Data: {10x2 cell}
DatabaseObject: [1x1 database]
6-138
procedures
RowLimit: 0
SQLQuery: '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]
curs.Data
ans =
[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'
6-139
querybuilder
Purpose Start SQL query builder GUI to import and export data
Syntax querybuilder
Tip To populate the VQB Schema and Catalog fields, you must
associate your user name with schemas or catalogs before starting VQB.
Examples For details about Visual Query Builder, including examples, see the
VQB Help menu or “Getting Started with Visual Query Builder” on
page 4-2.
6-140
querytimeout
querytimeout(curs)
ans =
10
6-141
register
Syntax register(d)
6-142
resultset
Description rset = resultset(curs) creates a resultset object rset for the cursor
curs. To get properties of rset, create a resultset metadata object using
rsmd, or make calls to rset using applications based on Oracle Java.
Run clearwarnings, isnullcolumn, and namecolumn on rset. Use
close to close the resultset, which frees up resources.
rset = resultset(curs)
rset =
Handle: [1x1 sun.jdbc.odbc.JdbcOdbcResultSet]
6-143
rollback
Syntax rollback(conn)
Note rollback does not roll back data in MySQL databases if the
database engine is not InnoDB.
Examples 1 Ensure that the AutoCommit flag for connection conn is off by
running:
get(conn,'AutoCommit')
ans =
off
2 Insert data contained in exdata into the columns DEPTNO, DNAME, and
LOC, in the table DEPT, for the data source conn.
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 now
contains the data it had before you ran the fastinsert function.
6-144
rows
conn = database('MySQL','username','pwd');
curs = fetch(curs);
6-145
rows
The Data property of curs contains the fetched data from the SELECT
query.
numrows = rows(curs)
numrows =
curs.Data
ans =
close(conn);
6-146
rsmd
rsmeta=rsmd(rset)
rsmeta =
Handle: [1x1 sun.jdbc.odbc.JdbcOdbcResultSetMetaData]
6-147
runsqlscript
6-148
runsqlscript
6-149
runsqlscript
conn = database('dbtoolboxdemo','','');
User names and passwords are not required for this connection.
results = runsqlscript(conn,'compare_sales.sql')
results =
The SQL script has two queries, and returns two results when executed.
results(2)
ans =
Attributes: []
6-150
runsqlscript
results(2).Data
ans =
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(results);
close(conn);
6-151
runsqlscript
conn = database('dbtoolboxdemo','','');
User names and passwords are not required for this connection.
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
results = runsqlscript(conn,'compare_sales.sql','rowInc',2)
results =
The SQL script has two queries, and returns two results when executed.
results(2).Data
ans =
res2 = fetch(results(2),2);
res2.Data
6-152
runsqlscript
ans =
close(results);
close(res2);
close(conn);
conn = database('dbtoolboxdemo','','');
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see database.
setdbprefs('FetchInBatches', 'yes')
Set appropriate batch size depending on the size of the resultset you
expect to fetch. For example, if you expect about a 100,000 rows in the
output, a batch size of 10,000 is a good starting point. The larger the
FetchBatchSize value, the fewer trips between Java and MATLAB,
and the memory consumption is greater for each batch. The optimal
value for FetchBatchSize is decided based on several factors like the
size per row being retrieved, the Java heap memory value, the driver’s
6-153
runsqlscript
default fetch size, and system architecture, and hence, may vary from
site to site. For details about estimating a value for FetchBatchSize,
see “Preference Settings for Large Data Import” on page 4-19.
setdbprefs('FetchBatchSize', '2')
results =
Definitions Batch
One or more SQL statements terminated by either a semicolon or the
keyword GO.
6-154
runsqlscript
6-155
runstoredprocedure
x = runstoredprocedure(c,'myprocnoparams')
x = runstoredprocedure(c,'myprocinonly',{2500,'Jones'})
x = runstoredprocedure(c,'myproc',{2500,'Jones'},{java.sql.Types.NUMERIC})
6-156
runstoredprocedure
6-157
set
6-158
set
Note For some databases, if you insert data and then close the
database connection without committing the data to the database, the
data gets committed automatically. Your database administrator can
tell you whether your database behaves this way.
6-159
set
Cursor Objects
The allowable property and value for a cursor object appear in the
following table.
Drivermanager Objects
The allowable property and value for a drivermanager object appear
in the following table.
help cursor/set
help database/set
help drivermanager/set
6-160
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 can
retrieve. Therefore, rerunning the fetch function returns no data.
6-161
set
get(conn, 'AutoCommit')
ans =
off
ans =
on
3 Insert a cell array exdata into column names colnames in the table
Growth.
6-162
set
1 First set the AutoCommit flag to off for database connection conn.
2 Insert a cell array exdata into the column names colnames in the
table Avg_Freight_Cost.
commit(conn)
rollback(conn)
6-163
set
The data in the table is now as it was before you ran update.
dm = drivermanager;
set(dm,'LoginTimeout',3);
logintimeout
ans =
3
6-164
setdbprefs
Purpose Set preferences for retrieval format, errors, NULLs, and more
Syntax setdbprefs
v = setdbprefs
setdbprefs(property)
setdbprefs(property,value)
setdbprefs(s)
6-165
setdbprefs
Data Types
char
s - Database preferences
structure
Database preferences, specified as a structure to include all the
database preferences you specify.
Data Types
struct
6-166
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'
For details about what each property and value mean, see “Using the
setdbprefs Function” on page 5-52.
Change a Preference
Set a database preference to another value.
setdbprefs ('NullNumberRead')
NullNumberRead: 'NaN'
Each NULL number in the database is read into the MATLAB workspace
as NaN.
Each NULL number in the database is read into the MATLAB workspace
as 0.
6-167
setdbprefs
setdbprefs('DataReturnFormat','cellarray');
conn = database('MySQL','username','pwd');
Alternatively, you can use the native ODBC interface for an ODBC
connection. For details, see the database function.
curs = exec(conn,...
'select productnumber,productdescription from producttable');
curs = fetch(curs,3);
curs.Data
ans =
setdbprefs('DataReturnFormat','numeric');
curs = exec(conn,...
'select productnumber,productdescription from producttable');
6-168
setdbprefs
curs = fetch(curs,3);
curs.Data
ans =
9 NaN
8 NaN
7 NaN
setdbprefs('DataReturnFormat','structure');
curs = exec(conn,...
'select productnumber,productdescription from producttable');
curs = fetch(curs,3);
curs.Data
ans =
curs.Data.productdescription
curs.Data.productnumber
6-169
setdbprefs
ans =
'Victorian Doll'
'Train Set'
'Engine Kit'
ans =
9
8
7
close(conn);
conn = database('MySQL','username','pwd');
setdbprefs('NullNumberWrite','NaN');
ex_data = {24,NaN,30.00};
Insert ex_data into the database using fastinsert with column names
productNumber, Quantity and Price.
6-170
setdbprefs
colnames = {'productNumber','Quantity','Price'};
fastinsert(conn,'inventoryTable',colnames,ex_data);
close(conn);
setdbprefs ('ErrorHandling','store');
conn = database('MySQL','username','pwd');
curs =
Attributes: []
Data: 0
DatabaseObject: [1x1 database]
RowLimit: 0
SQLQuery: 'select productdescription from producttable'
6-171
setdbprefs
setdbprefs ('ErrorHandling','report');
setdbprefs ('ErrorHandling','empty');
6-172
setdbprefs
curs =
Attributes: []
Data: []
DatabaseObject: [1x1 database]
RowLimit: 0
SQLQuery: 'select * from invalidTable'
Message: [1x102 char]
Type: 'Database Cursor Object'
ResultSet: 0
Cursor: 0
Statement: 0
Fetch: 0
close(conn);
Specify that NULL strings are read from the database into a MATLAB
matrix of doubles as 'NaN'.
setdbprefs({'NullStringRead';'DataReturnFormat'},...
6-173
setdbprefs
{'NaN';'numeric'});
For details about another way to change multiple settings, see “Assign
Values to a Structure” on page 6-174.
s.DataReturnFormat = 'numeric';
s.NullNumberRead = '0';
s.TempDirForRegistryOutput = 'C:\Work'
s =
DataReturnFormat: 'numeric'
NullNumberRead: '0'
TempDirForRegistryOutput: 'C:\Work'
setdbprefs(s);
setdbprefs
DataReturnFormat: 'numeric'
ErrorHandling: 'store'
NullNumberRead: '0'
NullNumberWrite: 'NaN'
NullStringRead: 'null'
NullStringWrite: 'null'
JDBCDataSourceFile: ''
UseRegistryForSources: 'yes'
TempDirForRegistryOutput: 'C:\Work'
DefaultRowPreFetch: '10000'
6-174
setdbprefs
FetchInBatches: 'no'
FetchBatchSize: '1000'
s = setdbprefs
s =
DataReturnFormat: 'cellarray'
ErrorHandling: 'store'
NullNumberRead: 'NaN'
NullNumberWrite: 'NaN'
NullStringRead: 'null'
NullStringWrite: 'null'
JDBCDataSourceFile: ''
UseRegistryForSources: 'yes'
TempDirForRegistryOutput: 'C:\Work'
DefaultRowPreFetch: '10000'
FetchInBatches: 'no'
FetchBatchSize: '1000'
Use the MATLAB tab completion feature when obtaining the value
for a preference.
s.U
Press the Tab key, and then Enter. MATLAB completes the field and
displays the value.
s.UseRegistryForSources
ans =
yes
6-175
setdbprefs
Save Preferences
You can save your preferences to a MAT-file to use them in future
MATLAB sessions.
For example, say that you need to reuse preferences that you set
for fetching large data. Assign the preferences to the variable
FetchLargeData and save them to a MAT-file FetchLargeDataPrefs in
your current folder.
FetchLargeData = setdbprefs;
save FetchLargeDataPrefs.mat FetchLargeData;
load FetchLargeDataPrefs.mat;
setdbprefs(FetchLargeData);
6-176
sql2native
6-177
supports
Syntax a = supports(dbmeta)
a = supports(dbmeta, 'property')
a.property
a = supports(dbmeta, 'GroupBy')
a =
1
a = supports(dbmeta)
a.GroupBy
a =
1
6-178
tableprivileges
Examples Get table privileges for the builds table in the schema geck for the
catalog msdb, for the database metadata object dbmeta.
tp = tableprivileges(dbmeta,'msdb','geck', 'builds')
tp =
'DELETE' 'INSERT' 'REFERENCES' ...
'SELECT' 'UPDATE'
6-179
tables
help dmd/tables
Examples Get the table names and types for the schema SCOTT in the catalog
orcl, for the database metadata object dbmeta.
t = tables(dbmeta,'orcl', 'SCOTT')
t =
'BONUS' 'TABLE'
'DEPT' 'TABLE'
'EMP' 'TABLE'
'SALGRADE' 'TABLE'
'TRIAL' 'TABLE'
6-180
unregister
Syntax unregister(d)
6-181
update
Tips • The order of records in your database is not constant. Use values of
column names to identify records.
• An error like the following may appear if your database table is
open in edit mode:
6-182
update
In this case, close the table and repeat the update function.
• An error like the following may appear if you try to run an update
operation that is identical to one that you just ran:
1 Define a cell array containing the column name that you are
updating, Quantity.
colnames = {'Quantity'}
exdata(1,1) = {2000}
6-183
update
exdata(1,1) = {30.00}
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 was
before you ran update.
A = 10000
B = 5000
6-184
update
6-185
versioncolumns
Examples Get a list of which columns automatically update when a row in the
table BONUS updates, in the schema SCOTT, in the catalog orcl, for the
database metadata object dbmeta.
vl = versioncolumns(dbmeta,'orcl','SCOTT','BONUS')
vl =
{}
The results are an empty set, indicating that no columns in the database
automatically update when a row value updates.
6-186
width
Examples Get the width of the first column of the fetched data set, curs:
colsize = width(curs, 1)
colsize =
11
6-187