How do I generate an SQL query that contains dates ?

조회 수: 5 (최근 30일)
Audrey Zammit
Audrey Zammit 2021년 5월 19일
답변: Hrishikesh Borate 2021년 5월 26일
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