%% Import Data from MySQL Database Table
% This example shows how to import data from a table in a MySQL® database into the MATLAB® workspace using the sqlread and fetch functions with the MySQL native interface.
%
%% Connect to Database
% Create a MySQL native interface database connection using the data source name MySQLDataSource and a user name and password. The MySQL database contains the table productTable.

datasource = "MySQLDataSource";
username = "root";
password = "matlab";
conn = mysql(datasource,username,password);

%
%% Import Data from Database Table Using sqlread Function
% Import product data from the database table productTable by using the sqlread function and the database connection. This function imports data as a MATLAB table.

tablename = "productTable";
data = sqlread(conn,tablename);

% Display the product number and description in the imported data.

data(:,[1 5])

%
%% Import Data from Database Table Using fetch Function
% Import product data from the database table productTable by using the fetch function and the database connection. Create an SQL query to import data that is sorted by product description alphabetically. The fetch function imports data as a MATLAB table.

sqlquery = "SELECT * FROM productTable ORDER BY productDescription ASC";
data = fetch(conn,sqlquery);

% Display the product number and description in the imported data.

data(:,[1 5])

%
%% Close Database Connection

close(conn)

% Copyright 2020 The MathWorks, Inc.