How do I generate an SQL query that contains dates ?
4 views (last 30 days)
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.
databasename = 'dataname';
username = 'name';
password = 'password';
driver = 'com.mysql.cj.jdbc.Driver';
url = 'url_of_the_database';
conn = database(databasename,username,password,driver,url);
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);
Hrishikesh Borate on 26 May 2021
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));