How do I generate an SQL query that contains dates ?

5 views (last 30 days)
Hello,
I've been struggling extracting some data from a database.
My code is as followed and the before last line doesn't work ..... The error message is "Unable to convert the text 'SELECT * FROM `data_marine_mrxb` WHERE date_time > '' to a datetime value because its format was not recognized." I don't know how to manage this because I need the format 'uuuu-MM-dd HH:mm:ss' but it seems not to be accepted.
javaaddpath('C:\Users\user\Downloads\mysql-connector-java-8.0.25.jar');
databasename = 'dataname';
username = 'name';
password = 'password';
driver = 'com.mysql.cj.jdbc.Driver';
url = 'url_of_the_database';
conn = database(databasename,username,password,driver,url);
% Query
t2 = datetime('now');
t1 = t2 - hours(1);
t2.Format = 'uuuu-MM-dd HH:mm:ss';
t1.Format = 'uuuu-MM-dd HH:mm:ss';
sqlquery = ["SELECT * FROM `data_marine_mrxb` WHERE date_time > '" t1 "'AND date_time < '" t2 "'"];
data = fetch(conn,sqlquery);

Answers (1)

Hrishikesh Borate
Hrishikesh Borate on 26 May 2021
Hi,
It’s my understanding that you are trying to define a SQL query based on the datetime values. Following is the code for the same:-
selectquery = 'SELECT * FROM `data_marine_mrxb` WHERE date_time BETWEEN ''%s'' AND ''%s'' ';
myQuery = sprintf(selectquery, datetime(t1), datetime(t2));

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!