Passing table name as a variable in Mysql query

37 ビュー (過去 30 日間)
Raj Tailor
Raj Tailor 2019 年 3 月 30 日
回答済み: Piyush Kumar 2024 年 9 月 30 日
Hello Experts,
I am trying to pass table name as a variable in mysql query, does anybody knows that is it possible or not?
PS:If I writes table name insead of variable, it works fine.
%I want something like this
datasource='mysql database name';
conn=database(datasource,'',''); %establishing connection to database
tablename='current_records'; %name of mysql table
sqlquery = ['SELECT id FROM ''' tablename ''''];
result = select(conn,sqlquery);
%This one works fine
datasource='mysql database name';
conn=database(datasource,'',''); %establishing connection to database
sqlquery = ['SELECT id FROM current_records'];
result = select(conn,sqlquery);

回答 (1 件)

Piyush Kumar
Piyush Kumar 2024 年 9 月 30 日
The issue is with the SQL query string. You should not use single quotes around the table name. Single quotes are used for string literals in SQL, not for identifiers like table names.
tablename='current_records'; %name of mysql table
sqlquery = ['SELECT id FROM ''' tablename ''''];
disp(sqlquery)
SELECT id FROM 'current_records'
Instead, you should use sprintf or proper string concatenation to correctly format the SQL query.
tablename = 'current_records'; % Name of the MySQL table
sqlquery = sprintf('SELECT id FROM %s', tablename);
disp(sqlquery)
SELECT id FROM current_records
tablename = 'current_records'; % Name of the MySQL table
sqlquery = ['SELECT id FROM ', tablename];
disp(sqlquery)
SELECT id FROM current_records

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by