How do I generate an SQL query that contains dates ?

5 次查看(过去 30 天)
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);

回答(1 个)

Hrishikesh Borate
Hrishikesh Borate 2021-5-26
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));

类别

Help CenterFile Exchange 中查找有关 Database Toolbox 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by