フィルターのクリア

How to modify the built-in 'fetch' function so that it can select columns flexibly?

1 回表示 (過去 30 日間)
Simon
Simon 2022 年 11 月 9 日
コメント済み: Simon 2022 年 11 月 10 日
I was trying to write a function which fetch only the columns I like from a MySQL table.
easy_fetch(conn, 'mytable', 'A', 'B') % error, incorrect sqlquery string
easy_fecth(conn, 'mytable', 'A,', 'B') % this works but clumsy
function T = easy_fetch (conn, tablename, varargin)
sqlquery = ['select ' varargin{:} ' from ' tablename]; % I don't know how to insert commas here.
T = fetch(conn, sqlquery);
end
That fuction does not create right sql query string because it doesn't have commas between A and B
wrong_string = 'select A B from mytable'.
fetch(conn, wrong_string) % error
% the correct query string should have commas between A and B
right_string = 'select A, B from mytable'
fecth(conn, right_string) % success
How would I put ',' between A and B in the easy_fetch function? Or is there better way to flexibly fetch columns? I have checked out a couple packages shared in File Exchange. None has codes I can use. Thanks for any suggestions.

採用された回答

Steven Lord
Steven Lord 2022 年 11 月 10 日
s = {'Larry', 'Curly', 'and Moe'}
s = 1×3 cell array
{'Larry'} {'Curly'} {'and Moe'}
s2 = strjoin(s, ', ')
s2 = 'Larry, Curly, and Moe'
  1 件のコメント
Simon
Simon 2022 年 11 月 10 日
I am very thankful for your solution. It works! The modified version does what I want.
T = easy_fetch(conn, 'mytable', 'A', 'B') % works smoothly :-)
%%
function T = easy_fetch (conn, tablename, varargin)
cols = strjoin(varargin, ',');
sqlquery = ['select ' cols ' from ' tablename];
T = fetch(conn, sqlquery);
end

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeDatabase Toolbox についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by