How to query a database by date range [duplicate] - java

This question already has answers here:
Searching between dates in SQL with JDBC?
(3 answers)
Closed 5 years ago.
I'm making a Java program that will determine the JComboBox values set default to get the user's input to choose within daily, weekly, monthly and yearly. Now I have an idea in monthly but my query returning an Exception error. Here is my code.
Calendar timer = Calendar.getInstance();
timer.getTime();
int month = timer.get(Calendar.MONTH);
int year = timer.get(Calendar.YEAR);
int day = timer.get(Calendar.DAY_OF_YEAR);
int week = timer.get(Calendar.WEEK_OF_YEAR);
String combovalue = comboBox.getSelectedItem().toString();
if(combovalue.equals("Monthly")) {
try {
String sql = "SELECT * FROM sales WHERE date between January and February";
pst = connection.prepareStatement(sql);
pst.setString(1, String.valueOf(day));
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
JOptionPane.showMessageDialog(null, "Monthly" );
}catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1 );
}

Let's just start with...
String sql = "SELECT * FROM sales WHERE date between January and February";
pst = connection.prepareStatement(sql);
pst.setString(1, String.valueOf(day));
The sql is invalid to start with, January and February should be quoted, but, since you're trying to use a PreparedStatement, there are no parameters, so pst.setString(1, String.valueOf(day)); will fail ... I mean, where is parameter 1 anyway?
I would recommend having a closer look at Using Prepared Statements
Instead, you should be using something like...
String sql = "SELECT * FROM sales WHERE date between ? and ?";
try (PreparedStatement pst = connection.prepareStatement(sql)) {
pst.setString(1, new java.sql.Date(fromDate.getTime()));
pst.setString(2, new java.sql.Date(toDate.getTime()));
try (ResultSet rs = pst.executeQuery()) {
table.setModel(DbUtils.resultSetToTableModel(rs));
}
JOptionPane.showMessageDialog(null, "Monthly");
} catch (SQLException exp) {
JOptionPane.showMessageDialog(null, ep);
}
This assumes that sales.date is an actual date/time type.
There are a number of ways to get the start/end dates, one of the better ways would be to use the newer Date/Time API, instead of the defunct Calendar API, for example...
LocalDate startDate = LocalDate.of(year, Month.JANUARY, 1);
LocalDate endDate = startDate.plusMonths(1);
You would then need to use...
pst.setString(1, java.sql.Date.valueOf(startDate));
pst.setString(2, java.sql.Date.valueOf(endDate));
to make them compatible with java.sql.Date
Updated...
Just to verify I wasn't going insane, I wrote this simple test class...
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.Month;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.h2.Driver");
try (Connection con = DriverManager.getConnection("jdbc:h2:mem:test")) {
con.setAutoCommit(true);
String make = "create table if not exists Test (id bigint identity, value date)";
try (Statement stmt = con.createStatement()) {
stmt.execute(make);
}
try (Statement stmt = con.createStatement()) {
System.out.println(">> Remove " + stmt.executeUpdate("delete from test") + " rows");
}
LocalDate ld = LocalDate.of(2017, Month.DECEMBER, 25);
for (int index = 0; index < 100; index++) {
insert(con, ld);
ld = ld.plusDays(5);
}
try (Statement stmt = con.createStatement()) {
try (ResultSet rs = stmt.executeQuery("select count(*) from test")) {
while (rs.next()) {
int count = rs.getInt(1);
System.out.println("Found " + count + " rows");
}
}
}
// String sql = "select value from test";
// try (PreparedStatement stmt = con.prepareStatement(sql)) {
// try (ResultSet rs = stmt.executeQuery()) {
// while (rs.next()) {
// System.out.println(rs.getObject(1));
// }
// }
// }
LocalDate startDate = LocalDate.of(2018, Month.JANUARY, 1);
LocalDate endDate = startDate.plusMonths(1);
String sql = "select value from test where value between ? and ?";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
stmt.setDate(1, java.sql.Date.valueOf(startDate));
stmt.setDate(2, java.sql.Date.valueOf(endDate));
System.out.println(startDate);
System.out.println(endDate);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
java.sql.Date date = rs.getDate(1);
System.out.println(date);
}
}
}
}
}
public static void insert(Connection con, LocalDate ld) throws SQLException {
String sql = "insert into test (value) values (?)";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
java.sql.Date date = java.sql.Date.valueOf(ld);
stmt.setDate(1, date);
stmt.executeUpdate();
}
}
}
It uses a H2 Database Engine in memory database, populates it with 100 dates from December 25th 2017 to May 9th 2019.
It then performs a query for values between January 1st 2018 and February 1st 2018 and prints
2018-01-01
2018-02-01
2018-01-04
2018-01-09
2018-01-14
2018-01-19
2018-01-24
2018-01-29
So, you need to make sure that you have valid values in your database. If you're not getting anything in your table, first, verify that the database actually returns something and that your query is valid for the data you are trying to get

You need to write date between in numeric values Jan as '01-01-2018', Feb '02-01-2018' so SELECT * FROM sales WHERE date between '01-01-2018' and '02-01-2018'
Calendar timer = Calendar.getInstance();
timer.getTime();
int month = timer.get(Calendar.MONTH);
int year = timer.get(Calendar.YEAR);
int day = timer.get(Calendar.DAY_OF_YEAR);
int week = timer.get(Calendar.WEEK_OF_YEAR);
String combovalue = comboBox.getSelectedItem().toString();
if(combovalue.equals("Monthly")) {
try {
String sql = "SELECT * FROM sales WHERE date between 01-01-2018 and 02-01-2018";
pst = connection.prepareStatement(sql);
pst.setString(1, String.valueOf(day));
rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
JOptionPane.showMessageDialog(null, "Monthly" );
}catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1 );
}

Define Sales.date and / or Try TRUNC(date) function. Or use Numeric value like
BETWEEN '01-JAN-2018' AND '01-FEB-2018'.
Remember to insert '' marks Around the date.

Related

Java/Groovy and MySQL: Checking if row exists in table

I am trying to check if a specific row exists in a table that includes two given parameters: record_id and modifiedDate. So far my code does not work.
public void doSomething(int RECORD_ID) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String modifiedDate = dateFormat.format(date);
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass");
Statement stmt = connection.createStatement();
String checkIfInDB = "select exists(select * from table where reference = ${RECORD_ID} and creation_date = '${modifiedDate}');"
ResultSet rs = stmt.executeQuery(checkIfInDB);
if(rs.next()) {
println "Query in db"
stmt.close();
connection.close();
return;
}
else {
String command = "INSERT INTO table(reference, creation_date) VALUES (${RECORD_ID}, '${modifiedDate}');"
stmt.executeUpdate(command)
println "Success"
stmt.close();
connection.close();
return;
}
}
If the user inserts a RECORD_ID and date that already exists, the program adds it to the table anyway, when it should print 'Query in db'.
I would appreciate any help to solve this issue.
Rather than listing what was wrong with the provided code I offer an example of a working example that could be used to help you along your journey...
public static void main(String[] args) {
int recordId = 1;
String jdbcSource = "jdbc:mysql://localhost:####/";
String user = "****";
String password = "****";
String checkIfInDB = "select count(*) as cnt from example_schema.example_table where example_table.reference = ? and example_table.creation_date = ?";
try (Connection connection = DriverManager.getConnection(jdbcSource, user, password)) {
PreparedStatement stmt = connection.prepareStatement(checkIfInDB);
stmt.setInt(1, recordId);
stmt.setDate(2, java.sql.Date.valueOf(LocalDate.now()));
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("at least one row matched");
return;
} else {
// to-do implement insert statement
return;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

I'm getting MySQL server version for the right syntax to use near '.null'

I'm getting this error and I don't why I tried the statement on workbench and it worked.
I'm looking also to improve my dates subtracting code basically I'm getting deadline from the table and I'm subtracting from today's date.
public boolean checkLessThanWeek(User userWhoWantsToExtendDeadline,BorrowedBook book) throws ParseException {
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Deadline FROM library_students.borrowedcopies WHERE LenderToID =" + "'" + userWhoWantsToExtendDeadline.getId()+ "'"+"And Barcode="+"."+book.getbookID());
if (rs.next()) {
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Date deadline = format.parse(rs.getString(1));
Date date=new Date();
String today=format.format(date.getDate());
date = format.parse(today);
long milliseconds=date.getTime()-deadline.getTime();
long days = milliseconds / (1000 * 60 * 60 * 24);
System.out.print(days);
}
rs.close();
return true;
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
It is most likely because book.getbookID() returns null and because you for some reason have a dot (.) before it in your Sql. Besides this it is preferred to have a parameterized Sql statement using ? and also basic error handling is a good thing.
if (userWhoWantsToExtendDeadline == null || book == null || book.getbookID() == null {
//throw exception perhaps or log?
return false;
}
String query = "SELECT Deadline FROM library_students.borrowedcopies WHERE LenderToID = ? AND Barcode = ?";
Statement stmt = con.createStatement(query);
stmt.setInt(1, userWhoWantsToExtendDeadline.getId());
stmt.setString(2, book.getbookID());
ResultSet rs = stmt.executeQuery();
Note that I assumed your first parameter is an int and the second one is a String but of course ths might need to be changed

Select between dates SQLite

I am trying to write a query in my Java program to select records between two dates. I have built my dates as such:
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy", Locale.ENGLISH);
Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
When I query the DB I get the attached.
I cannot get the query to select any records (e.g. between 01/01/15 and 12/31/15). I have tried all sorts of combos of strftime, but to no avail.
I am a noob to Java and SQLite, so I am sure it is a dumb user error.
Sorry about my reply below.
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '01/01/15' AND '12/31/15'
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '2015/01/01' AND '2015/12/31'
SELECT Course, date DateSort FROM Peter_SCORE_TBL WHERE DateSort BETWEEN '2015-01-01' AND '2015-12-31'
SELECT Course, date DateSort FROM Peter_SCORE_TBL strftime('%m/%d/%Y', DateSort) BETWEEN '01/01/15' AND '12/31/15'
Above is what I have tried in Firefox SQLite Manager extension.
EDIT:
In the above, I had DateSort defined as DATETIME. I have changed to DATE and VARCHAR and run the above queries, nothing selected.
I have also tried:
SELECT * FROM Peter_SCORE_TBL WHERE date(DateSort) BETWEEN date('01/01/15') AND date('12/31/15')
SELECT * FROM Peter_SCORE_TBL WHERE date(DateSort) BETWEEN date('2015-01-01') AND date('2015-12-31')
Neither worked. Don't know what else to try.
EDIT:
I grabbed this small piece of code and modified it to test. It does not work. What am I missing?
public class SQLiteTest
{
public static void main(String[] args) throws Exception
{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:/Users/peterream/Desktop/Desktop Archive/Crashplan/sqlitetest.sqlite");
Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists people;");
stat.executeUpdate("create table people (name TEXT, occupation TEXT, DateSort INTEGER);");
PreparedStatement prep = conn.prepareStatement(
"insert into people values (?, ?, ?);");
prep.setString(1, "Gandhi");
prep.setString(2, "politics");
prep.setDate(3, convertSQLDate("2016-04-08"));
prep.addBatch();
prep.setString(1, "Turing");
prep.setString(2, "computers");
prep.setDate(3, convertSQLDate("2015-04-08"));
prep.addBatch();
prep.setString(1, "Wittgenstein");
prep.setString(2, "smartypants");
prep.setDate(3, convertSQLDate("2014-04-08"));
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);
ResultSet rs = stat.executeQuery("select * from people WHERE strftime('%Y-%m-%d', DateSort) BETWEEN '2015-01-01' AND '2015-12-31';");
while (rs.next()) {
System.out.println("name = " + rs.getString("name"));
System.out.println("job = " + rs.getString("occupation"));
System.out.println("DateSort = " + rs.getString("DateSort"));
}
rs.close();
conn.close();
}
/**
**
* This method converts input string date to sql date format
*
* #param String sqlDateIn (MM/dd/yy)
* #return java.sql.Date returnDate
*/
public static java.sql.Date convertSQLDate (String sqlDateIn)
{
java.sql.Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
java.util.Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
catch (ParseException e)
{
e.printStackTrace();
}
return returnDate;
}
}
I am looking to select 1 row 2015-04-08.

Conversion failed when converting date or time from character string in java

I have created two methods in java ,one of which returns the database server time and other returns the one hour ago time of database server.Now I have to use these two date time into a sql query.The code for retrieving database server time is:-
public String database_Time() throws SQLException
{
con = getConnection();
String sql = "select GETDATE()";
clstmt = con.prepareCall(sql);
clstmt.execute();
rs = clstmt.getResultSet();
while(rs.next()) {
timestr= rs.getString(1);
}
System.out.println("database time is" +timestr);
return timestr;
}
Another method for retrieving one hour ago time is
public String previostime() throws ParseException, SQLException
{
database_Time();
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(timestr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
hours--;
calendar.set(Calendar.HOUR_OF_DAY, hours);
fixedDate = calendar.getTime();
stringDate = simpleDateFormat.format(fixedDate );
System.out.println("previous date is"+(stringDate));
System.out.println("current date is"+timestr);
return stringDate;
}
But when I use stringDate and timestr in sql query ,then I got an error that com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting date and/or time from character string.
Code for sql query is:-
String sql = "select * from vs1_bag where logtime between 'stringDate'and 'timestr' ";
Edit:-
Method through which I will retrieve the time,and will use it in my application is:-
public String [] getChartTime() throws SQLException, ParseException
{
List<String> tStr = new ArrayList<String>();
database_Time();
String atime[] = null;
previostime();
getConnection();
try
{
con = getConnection();
stmt = con.createStatement();
String sql = "select * from vs1_bag where logtime between 'stringDate'and 'timestr' ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while(rs.next()) {
// Just get the value of the column, and add it to the list
tStr.add(rs.getString(1).substring(11,16));
}
}
catch( Exception e )
{
System.out.println("\nException in Bean in getDbTable(String code):"+e);
}
finally
{
closeConnection();
}
// I would return the list here, but let's convert it to an array
atime= tStr.toArray(new String[tStr.size()]);
return atime;
}
How to resolve it.
shouldn't it be like this? :
String sql = "select * from vs1_bag where logtime between '"+stringDate+"' and '"+timestr+"' ";

how to pass variable value from one method onto another as a parameter of database query in java

I have retrieved the value of logtime from database and calculated one hour ago time from the retrieved logtime.the code for retrieving logtime is
public String database_Time() {
try {
con = getConnection();
String sql = "select max(logtime) from vacuum_analog_1mins";
clstmt = con.prepareCall(sql);
clstmt.execute();
rs = clstmt.getResultSet();
while (rs.next()) {
timestr = rs.getString(1);
}
} catch (Exception e) {
System.out.println("\nException in Bean in getDbTable(String code):" + e);
} finally {
closeConnection();
}
return timestr;
}
Code to calculate one hour ago time is:
public Date previostime() throws ParseException
{
database_Time();
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(timestr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
hours--;
calendar.set(Calendar.HOUR_OF_DAY, hours);
Date fixedDate = calendar.getTime();
System.out.println("previous date is" + (fixedDate));
System.out.println("current date is" + timestr);
return fixedDate;
}
Now I want to use these two variables fixedDate and timestr in my another method where these variables will be used as parameters of a sqlquery as:
List < String > timeStr = new ArrayList < String > ();
database_Time();
String atime[] = null;
database_Time();
previostime();
getConnection();
try {
con = getConnection();
String sql = "exec vcs_gauge #gauge_name=?,#first_rec_time=?,#last_rec_time=?";
clstmt = con.prepareCall(sql);
clstmt.setString(1, "vs1_bag");
clstmt.setString(2, "fixedDate");
clstmt.setString(3, "timestr");
clstmt.execute();
rs = clstmt.getResultSet();
while (rs.next()) {
// Just get the value of the column, and add it to the list
timeStr.add(rs.getString(1).substring(11, 16));
}
But no result.Please help me where I'm going wrong.I have declared these variables as global also.
This two row aren't correct
clstmt.setString(2, "fixedDate");
clstmt.setString(3, "timestr");
if in sql they are Date type try this:
clstmt.setDate(2, java.sql.Date(fixedDate.getTime()));
clstmt.setDate(3, java.sql.Date.valueOf(timestr));

Categories