How do I generate an SQL query that contains dates ?

5 vues (au cours des 30 derniers jours)
Audrey Zammit
Audrey Zammit le 19 Mai 2021
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);

Réponses (1)

Hrishikesh Borate
Hrishikesh Borate le 26 Mai 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));

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by