Select between dates SQLite - java

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.

Related

How to query a database by date range [duplicate]

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.

JDBC not working as intended when inserting dates into Database

my code seems to now work as intended and i can't seem to understand why . I'm trying to update a date from the database with anotherDate+14. The problem is all the updated dates have the same value. The code works when i try debugging it , but i got code different results in the db .
Here is the code :
String query="SELECT issueTime from issue";
ResultSet rs=DatabaseHandler.getInstance().execQuery(query);
try {
while(rs.next()){
java.sql.Date dbTime=rs.getDate("issueTime");
java.sql.Date initialDBTime=dbTime;
java.util.Date utilDate = new java.util.Date(dbTime.getTime());
Calendar cal=Calendar.getInstance();
cal.setTime(utilDate);
cal.add(Calendar.DATE,14);
utilDate= cal.getTime();
dbTime=new java.sql.Date(utilDate.getTime());
System.out.println("return date " + dbTime+ " Initial db time " + initialDBTime);
String qu = "UPDATE issue SET return_date=? WHERE issueTime = ?";
PreparedStatement pstmt=DatabaseHandler.getInstance().getConnection().prepareStatement(qu);
pstmt.setDate(1,dbTime);
pstmt.setDate(2, initialDBTime);
pstmt.executeUpdate();
Database results:
UPDATE : Found the problem , i was selecting only issueTime from my table .
Changed :
String query="SELECT * from issue";
Thank you for your help .
Issuetime and return_date have DateTime format, try to use Timestamp instead of Date. Here an example if you want to add 14 days:
public class TestUpdate {
public static void main(String[] args) throws ClassNotFoundException, SQLException{
TestsJdbc jdbc= new TestsJdbc();
jdbc.connect();
Connection con =jdbc.getConnection();
List<java.sql.Timestamp> listIssueDate=getIssueDate(con );
updateReturnDate(con, listIssueDate);
jdbc.closeConnexion();
}
public static java.util.Date tmsToUtilDate(java.sql.Timestamp timestamp) {
long milliseconds = timestamp.getTime() + (timestamp.getNanos() / 1000000);
return new java.util.Date(milliseconds);
}
public static java.sql.Timestamp getTimestamp(java.util.Date date){
return date == null ? null : new java.sql.Timestamp(date.getTime());
}
public static java.util.Date addDay(java.util.Date curDate, int nbDay){
Calendar cal = Calendar.getInstance();
cal.setTime(curDate);
cal.add(Calendar.DATE, nbDay); // add 10 days
return cal.getTime();
}
public static List<java.sql.Timestamp> getIssueDate(Connection connexion) throws SQLException{
String query="SELECT issueTime from issue";
Statement statement;
List<java.sql.Timestamp> listDate= new ArrayList<java.sql.Timestamp>();
try {
statement = (Statement) connexion.createStatement();
ResultSet rs = statement.executeQuery( query);
while (rs.next()) {
//java.sql.Time dbSqlTime = rs.getTime("issueTime");//only time
//java.sql.Date dbSqlDate = rs.getDate("issueTime");//Date ex :YYYY-MM-DD
java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp("issueTime");// timestamp Date ex :YYYY-MM-DD hh:mm:ss
System.out.println("date:"+dbSqlTimestamp);
System.out.println();
listDate.add(dbSqlTimestamp);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listDate;
}
public static void updateReturnDate(Connection connexion, List<java.sql.Timestamp> listIssueDate) throws SQLException
{
for(java.sql.Timestamp sqlIssueDate:listIssueDate){
//
java.util.Date tempUtilDate=tmsToUtilDate(sqlIssueDate);
java.util.Date newutilDate=addDay(tempUtilDate, 14);
java.sql.Timestamp returnDate=getTimestamp(newutilDate);
System.out.println(returnDate.getTime());
System.out.println(sqlIssueDate);
//Test
String query="UPDATE issue SET return_date=? WHERE issueTime = ?";
PreparedStatement preparedStmt = connexion.prepareStatement(query);
preparedStmt.setTimestamp(1, returnDate);
preparedStmt.setTimestamp(2, sqlIssueDate);
// execute the java preparedstatement
preparedStmt.executeUpdate();
}
//connexion.close();
}
}
a screenshot of table before:
the table after update :

java jdbc select from where with string type

I am trying to solve a problem of my code. In the following code, it contains JComboBox which have a list of month. When I click on January, I want to show all the details of that month.
private void jComboBox1_MonthsActionPerformed(java.awt.event.ActionEvent evt) {
String selection = (String)jComboBox1_Months.getSelectedItem();
if(selection.equals("January")){
try{
String sql = "select * from booking where Date = ??/01/??"; //problem
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
viewBookingTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
}
}
}
The format for the Date is 12/01/16 in the Database with type CHAR.
Please help. Thank you very much in advance.
Even though I suggest revisiting your aprroach and favor the usage of the java.sql.Date type, you can select the desired rows using a LIKE predicate:
String sql = "SELECT * FROM booking WHERE Date LIKE '%/01/%'";
Yo could do that:
String sql = "select * from booking where SUBSTR(Date,4,2) = "01";
int index = jComboBox1_Months.getSelectedIndex() + 1;
String sql = "SELECT * FROM `booking` WHERE `date` like '%?%';
pst = conn.prepareStatement(sql);
pst.setObject(1, index);
...

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+"' ";

Cant get records between two dates

My problem is that I can't fetch all records that are between two dates.
I have two JDateChoosers. When I select two dates like '10-apr-2011' to '20-apr-2011' I want all the records between those dates to be displayed in my JList. But I can't get any results in the JList.
I am using mysql database.
private void Display(java.awt.event.ActionEvent evt) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
(Connection)DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","ubuntu123");
java.util.Date jd = jDateChooser1.getDate();
java.util.Date jd1 = jDateChooser2.getDate();
// PreparedStatement stmt = (PreparedStatement) con.prepareStatement("select date from invoice where date = ?);
// PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date BETWEEN ' ' AND ' '");
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= '+jd + ' AND date <= '+jd1 + '");
pstmt.execute();
ResultSet rs = pstmt.getResultSet();
int i =0;
DefaultListModel listModel = new DefaultListModel();
while(rs.next())
{
String [] data;
data = new String[100];
data [i] = rs.getString("date");
jList1.setModel(listModel);
listModel.addElement(data [i]);
i = i+1;
}
}
catch (Exception e)
{
System.out.println("2nd catch " + e);
}
}
Can anyone tell me where my mistake is?
Thanks in advance..
Since this is a PreparedStatement you can try:
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= ? AND date <= ?");
pstmt.setDate(1,new java.sql.Date(jd.getTime()));
pstmt.setDate(2,new java.sql.Date(jd1.getTime()));
ResultSet rs = pstmt.executeQuery();
You need to take out jList1.setModel(listModel); out of the loop
while(rs.next())
{
String [] data;
data = new String[100];
data [i] = rs.getString("date");
//jList1.setModel(listModel);
listModel.addElement(data [i]);
i = i+1;
}
jList1.setModel(listModel);
You need to alter your query. Something like this:-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String jdStr = sdf.format(jd);
String jd1Str = sdf.format(jd1);
PreparedStatement pstmt = (PreparedStatement) con.prepareStatement("SELECT date FROM invoice WHERE date >= '" + jdStr + "' AND date <= '" + jd1Str + "'");
Previously, in your query, the 2 parameters, jd & jd1 were not getting append. This change will now append it in the query. The problem was with the jd & jd1 not correctly being appended in the query.
Note:- I've added a SDF so that you could format your date in format needed and append it to the query.
never to create an GUI Objects inside hard and long running JDBC, nor inside try - catch - finally, on exception those Object never will be created
DefaultListModel listModel = new DefaultListModel(); should be created an local variable, and then isn't required to recreate a new XxxListModel on runtime
have to remove all elements from listModel, otherwise new Items will be appended to the end of JList
definition for String [] data; and data = new String[100]; and data [i] = rs.getString("date"); inside while(rs.next()) { are quite useless, because database records are stored from this array in XxxListModel, and accessible for other usage for elsewhere
Connection, PreparedStatement and ResultSet should be closed in finally block (try - catch - finally), otheriwe these Objects stays (and increasing) in JVM memory,
are you sure dates in SQL and date from java.util.Date are in the same format?
Try using
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
to check whenever they are same.
jd and jd1 by default would differ by SQL date #see SQL Dates
This is not the correct way of using PreparedStatement, which is already prepared to handle Dates, so you should not covert them to String. Your code should look like this:
PreparedStatement pstmt = ...
pstmt.setDate(...)
Also your query String is not really using the jd as a variable, you misused ' and "

Categories