In my java project I want to list the values of a table
programtable.
There are four fields programid, programname, startdate and enddate in table.
I want to list the details of programs done in today.
The startdate and enddate are in database datatype as TIMESTAMP. Help me to find the query to get the details of programs done on today.
I add my code to this. I use this method. But its not work,
String todayDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
todayDatem=todayDate+" 00:00:00";
todayDaten=todayDate+" 23:59:59";
Timestamp timestamp1 = Timestamp.valueOf(todayDatem);
Timestamp timestamp2 = Timestamp.valueOf(todayDaten);
System.out.println("timestamp1:"+timestamp1+timestamp2);
String sql3 = "select * form programtable where startdate between '”+timestamp1+”' and '”+timestamp2+”'";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<programmodel> pgm = jdbcTemplate.query(sql3, ParameterizedBeanPropertyRowMapper.newInstance(programmodel .class));
It is better to use placeholders instead of text dates in the query:
java.sql.Date d1 = new java.sql.Date(System.currentTimeMillis());
java.sql.Date d2 = new java.sql.Date(System.currentTimeMillis() + 24 * 3600 * 1000);
String sql3 = "select * from programtable where startdate between ? and ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<programmodel> pgm = jdbcTemplate.query(sql3, ParameterizedBeanPropertyRowMapper.newInstance(programmodel.class), d1, d2);
If you mean started and finished today
SELECT *
FROM programtable
WHERE startdate = CURDATE() AND enddate = CURDATE();
If you mean started today
SELECT *
FROM programtable
WHERE startdate = CURDATE();
If you mean finished today
SELECT *
FROM programtable
WHERE enddate = CURDATE();
Related
I need to display to the table all the records who has is created_at this month. the format is mmm dd yyyy, Using java and sqlite
I have the column "Start" in my database, if the month of the date is this month, it has to appear in the table.
I Tried this code below,, pls guide me.
i need to select all the records, within the month.
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
c = Calendar.getInstance(); // reset
String today = dateFormat.format(c.getTime());
int month = c.get(Calendar.MONTH) + 1;
String sql = "SELECT Firstname FROM Members_Tbl WHERE End = '" + month
+ "'";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
monthlyreports.setModel(DbUtils.resultSetToTableModel(rs));
rs.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
java.time
I have not tested (haven’t got SQLite installed), but I believe the following should work:
DateTimeFormatter monthPatternFormatter = DateTimeFormatter.ofPattern("MMM '%' uuuu", Locale.ENGLISH);
YearMonth currentMonth = YearMonth.now(ZoneId.of("Australia/Melbourne"));
String sql = "SELECT Firstname FROM Members_Tbl WHERE Start like ?;";
pst = con.prepareStatement(sql);
String monthPattern = currentMonth.format(monthPatternFormatter);
pst.setString(1, monthPattern);
rs = pst.executeQuery();
I am taking your word for it when you say that the format in your database is mmm dd yyyy, for example Apr 11 2019. I am assuming English month abbreviations.
I would recommend storing ISO 8601 standard date strings in your database, though. It goes like 2019-04-11. Then your format pattern string would be uuuu-MM-'%'. Or you might compare strings using <= and <, which would probably be more efficient.
The date/time classes that you were using, SimpleDateFormat and Calendar, are poorly designed and fortunately long outdated. Instead I am using java.time, the modern Java date and time API. It is so much nicer to work with.
Links
Oracle tutorial: Date Time explaining how to use java.time.
SQLite Like: Querying Data Based On Pattern Matching
You could use (see below) the SQLite substr core function :-
String sql = "SELECT Firstname FROM Members_Tbl WHERE substr(Start,1,2) = '" + month + "'";
BUT that would include all years.
So you may want :-
String sql = "SELECT Firstname FROM Members_Tbl WHERE substr(Start,1,2) = '" + month + "' AND substr(Start,7,4) = '" + the_respective_year + "'";
Notes
If MM or DD are not always 2 characters (e.g. 1/9/2019) then the above would not work properly.
The recommended way is to store dates in YYYY-MM-DD format (or any of the time string formats from the link). You can then use the SQLite DateTime functions.
String sql = "select * from Members_Tbl WHERE strftime('%m', Start) == strftime('%m', 'now')";
This is the query I used, and after several searches the date should be YYYY-MM-DD.
thank you everyone for your cooperation.
Your SimpleDateFormat object must match the format stored in the table if you want to compare the months.
You must compare also the year not just the month.
It is always safer to use placeholders inside the sql statement instead of concatenating the parameters:
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
c = Calendar.getInstance(); // reset
String today = dateFormat.format(c.getTime());
String sql =
"SELECT Firstname FROM Members_Tbl WHERE " +
"substr(Start, 1, 3) = ? AND substr(Start, 8, 4) = ?";
pst = con.prepareStatement(sql);
pst.setString(1, today.substring(0, 3));
pst.setString(2, today.substring(7));
rs = pst.executeQuery();
monthlyreports.setModel(DbUtils.resultSetToTableModel(rs));
rs.close();
Edit
Since you changed the format of the dates to YYYY-MM-DD,
you can use this query:
String sql = "select * from Members_Tbl WHERE strftime('%Y-%m', Start) = strftime('%Y-%m', 'now')";
How to write the java criteria query for hibernate3.
Select * from some_table where created_at between DATE_SUB(curdate() , INTERVAL 8 DAY) and date_sub(curdate() ,INTERVAL 2 DAY)
CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<MyEntity> criteria = builder.createQuery(MyEntity.class);
Root<MyEntity> root = criteria.from(MyEntity.class);
Using the old java.util.Calendar and java.util.Date.
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, -8);
Date eightDaysAgo = now.getTime();
now.add(Calendar.DATE, 6);
Date twoDaysAgo = now.getTime();
Expression<Date> createdAt = root.<Date>get("created_at"); // choose the name of the property in Entity definition
Predicate predicate = builder.between(createdAt, twoDaysAgo, eightDaysAgo);
criteria.where(predicate);
I have a table
Id AuctionName URL StartDate EndDate
1 auction1 image 2015-01-11 22:27:21 2015-01-12 14:25:22
2 auction2 video 2015-01-12 05:30:50.0 2015-01-14 08:18:10
I get the currentTimeStamp using Java like this:
public Timestamp getCurrentTimestamp(){
java.util.Date date= new java.util.Date();
SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDate=dateFormater.format(date);
Timestamp currentTimestamp=Timestamp.valueOf(currentDate);
System.out.println(currentTimestamp);
return currentTimestamp;
}
This is my output.
2015-01-12 05:30:50.0
What is the right SQLQuery to retrieve currentAuctions. I would appreciate some help.
SELECT id, AuctionName FROM auctiontable WHERE (NOW() BETWEEN StartDate AND EndDate);
You could altenatively replace NOW() with the string formed in your Java code, but this is cleaner.
below is my stored procedure
create procedure sp_process_job(#request_id varchar(25), #host varchar(20),
created_on varchar(25)
)
as
begin
set dateformat mdy
SELECT CAST(#created_on as datetime)
insert into t_job_details(request_id ,host, created_on)
values(#request_id,#host,#created_on)
end
When I cast date using SELECT CAST(#created_on as datetime)
I get output as 2012-06-22 00:00:00.0 Time is 00:00:00.0
I want it as 12:45:06.0. Why I get 0 in all places?
Edit:
Calling the above procedure from java code
Date date = new Date();
Date insert_date = new java.sql.Date(date.getTime());
String insertquery = "{ call sp_process_job (?,?,?) }";
cs = con.prepareCall(insertquery.toString());
cs.setString(1, id);
cs.setString(2, host);
cs.setDate(3, (java.sql.Date) insert_date);
cs.execute();
con.commit();
I guess you should use java.sql.Timestamp in the Java code instead of java.sql.date which saves only date not time. And also cs.setTimestamp
java.sql.Timestamp insert_date = new java.sql.Timestamp(date.getTime());
....
cs.setTimestamp(3, insert_date);
In oracle I have dates in format
17-April-2011 19:20:23.707000000
I would like to retrieve all orders for 17-04-2011.
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);
Criteria criteria =
session.createCriteria(Order.class);
Criterion restrictDate = Restrictions.like("orderDate",date);
but it brings me empty result:
Why do you use Restrictions.like(...)?
You should use Restrictions.eq(...).
Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column.
Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.
For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).
In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).
Your date object you got with the code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);
This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.
This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".
If you want to retrieve all entries of your database from a given day, you will have to use the following code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
// Create date 17-04-2011 - 00h00
Date minDate = formatter.parse(myDate);
// Create date 18-04-2011 - 00h00
// -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
Conjunction and = Restrictions.conjunction();
// The order date must be >= 17-04-2011 - 00h00
and.add( Restrictions.ge("orderDate", minDate) );
// And the order date must be < 18-04-2011 - 00h00
and.add( Restrictions.lt("orderDate", maxDate) );
By using this way you can get the list of selected records.
GregorianCalendar gregorianCalendar = new GregorianCalendar();
Criteria cri = session.createCriteria(ProjectActivities.class);
cri.add(Restrictions.ge("EffectiveFrom", gregorianCalendar.getTime()));
List list = cri.list();
All the Records will be generated into list which are greater than or equal to '08-Oct-2012' or else pass the date of user acceptance date at 2nd parameter of Restrictions (gregorianCalendar.getTime()) of criteria to get the records.
If the column is a timestamp you can do the following:
if(fromDate!=null){
criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')"));
}
if(toDate!=null){
criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')"));
}
resultDB = criteria.list();
try this,
String dateStr = "17-April-2011 19:20:23.707000000 ";
Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String newDate = format.format(dateForm);
Calendar today = Calendar.getInstance();
Date fromDate = format.parse(newDate);
today.setTime(fromDate);
today.add(Calendar.DAY_OF_YEAR, 1);
Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.add(Restrictions.ge("dateFieldName", fromDate));
crit.add(Restrictions.le("dateFieldName", toDate));
return crit.list();