How to specifya a sql query if the criteria is a cell array?
1 次查看(过去 30 天)
显示 更早的评论
I've got a cell array like this sinkname = [washington newyork seattle]
and I'm connecting to a database and trying to extract the rows of data that have the exact same sinknames with the above cell array.
So I wrote the command like this: cur = exec(conn,'select city,people from map where city in sinkname');
I tried to add brackets/quotes/parenthesis around sinkname in the above command, but nothing worked.
What is the correct format of writing such query? Or is it impossible to set a where criteria like this?
My real cell array is very large so I can't type all the names in the 'where' criteria.
Thank you guys for help!
0 个评论
回答(1 个)
Sean de Wolski
2014-2-4
If you're using R2013a or newer, use strjoin to turn the cell into a string:
sinkname = {'washington' 'newyork' 'seattle'};
str = ['Select person where city in ' strjoin(sinkname)]
1 个评论
dleal
2021-4-27
I am getting an error doing something similar:
>> t = {'A','B','C'}
t =
1×3 cell array
{'A'} {'B'} {'C'}
>> T = strjoin(t)
ans =
'A B C'
>> query1 = ['SELECT * FROM testDB WHERE Col1 IN ',T]
query1 =
'SELECT * FROM testDB WHERE Col1 IN A B C'
JDBC Driver Error: [SQLITE_ERROR] SQL error or missing database (near "B": syntax error)
I dont get this error if I simply consult "B" individually:
query1 = ['SELECT * FROM testDB WHERE Col1 = ',T{2}]
Shouldn't I have quotes around every item in T? Shouldn't the be separated by commas and within brackets?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Database Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!