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])
ans=10×2 table
productNumber productDescription
_____________ __________________
9 "Victorian Doll"
8 "Train Set"
7 "Engine Kit"
2 "Painting Set"
4 "Space Cruiser"
1 "Building Blocks"
5 "Tin Soldier"
6 "Sail Boat"
3 "Slinky"
10 "Teddy Bear"
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])
ans=10×2 table
productNumber productDescription
_____________ __________________
1 "Building Blocks"
7 "Engine Kit"
2 "Painting Set"
6 "Sail Boat"
3 "Slinky"
4 "Space Cruiser"
10 "Teddy Bear"
5 "Tin Soldier"
8 "Train Set"
9 "Victorian Doll"
Close Database Connection
close(conn)
See Also
mysql | close | sqlread | executeSQLScript