Documentation Center

  • Trial Software
  • Product Updates

Importing Data from Databases

This example demonstrates a sample workflow on a demonstration database called dbtoolboxdemo.

  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.


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

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

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

    • The username and password

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

    Enter conn at the command prompt to see the data.

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

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

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

    • conn, the name of the connection object

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

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

    The exec function returns the MATLAB variable curs.

  5. The returned data contains strings, so you must convert it to a format that supports strings. Use setdbprefs to specify the format 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:

Was this topic helpful?