sqlread specific columns/variables from a MySQL table

I want to import to Matlab one or a couple specific columns from a table that is stored in MySQL database. sqlread(conn, tablename) would import the whole table. I tried playing around with opts. it didn't work. Is there any way to make this work? Or should I try using sql query script? Thanks!
opts = databaseImportOptions(conn, tablename);
opts = setoptions(opts, 'SelectedVaraibleNames', {'wanted_column'}); % error message

5 commentaires

What was the error message? Note there is a typo in your post--"SelectedVaraibleNames" is mis-spelled. Is it mis-spelled in your code too?
The spelling in my real codes is correct. I misspelled it in this post. The error message I had was
Expected wanted_column options to match one of these values:
'MissingRule', 'Name', 'Type', 'FillValue', 'WhitespaceRule', 'TextCaseRule'
The input, 'SelectedVariableNames', did not match any of the valid values.
@Walter Roberson, @Jeff Miller Thanks for pointing out the misspelling in the codes. After I corrected that, I tried
opts = databaseImportOptions(conn, "myTable")
opts.SelectedVariableNames = {'wanted_cloumn'}
And I got the error message:
------------------------- Error Message --------------------
Unable to use database import options with
'SELECT * from myTable'.
[T,metadata] = fetch(connect,sqlquery,optsObject,'MaxRows',maxRows);
data = sqlreadHook(connect,query,optsObject,maxRows,preservenames,isvarnamerulespecified);
----------------------------
The correct SQL query should be
SELECT wanted_column FROM DATABASE.myTable;
Matlab had not translated opts.SelectedVariableNames = wanted_column and mysqlread(....., opts) into that sql query. Instead, it translated to Select * from myTable. I guess I didn't understand how the sql input options work at all.
So I ran debugging. In connection.m, I found
%Construct the query
querybuilder = database.internal.utilities.SQLQueryBuilder;
querybuilder = querybuilder.select("*").from(tablename);
%.....
querybuilder = dispatcher.dispatch(rowFilter,querybuilder,connect.DatabaseProductName);
query = strtrim(querybuilder.SQLQuery);
Obviously, the querybuilder is not affected by opts.SelectedVariableNames at all. And it seems that, according to the way query is made, it's impossible to select specific columns for sql import.

Connectez-vous pour commenter.

Réponses (2)

The answer to my own questiion is fetch. sqlread always reads in the whole table.
sqlquery = 'select wanted_column from myTable';
wanted = fetch(conn, sqlquery)
opts = setoptions(opts, 'SelectedVariableNames', {'wanted_column'});
You had 'SelectedVaraibleNames' instead of 'SelectedVariableNames'

Produits

Version

R2023a

Tags

Question posée :

le 18 Jan 2025

Réponse apportée :

le 19 Jan 2025

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by