Insert dd/mm/yyyy date format into database table - java

I am trying to insert a dd/mm/yyyy date format into my database table. The data type for date column in database is date and my SQL insert statement is:
INSERT INTO sm_product(productName, productDescription, productPrice, productQuantity, productStatus)
VALUES ('" + name + "', '" + desc + "', " + price + ", " + quantity + ", 'Available', '" + date + "'";
However, netbeans shows me an error when I added the date variable into the SQL statement.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
And it stores the date as:
Wed Jun 19 17:42:26 SGT 2013
And I got my dd/mm/yyyy date format in user interface:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
dateFormat.format(date);
This format is not I wanted. So I wonder how should I amend my SQL statement to fix the problem.
Thanks in advance.

If you are using SQL Server , you can use
REPLACE(CONVERT(VARCHAR(11),date,105),'-','/')

If you insert following format sting into query, record will be updated
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = new Date();
String formatDate = dateFormat.format(date);

Related

How to Select SQLIte columns based on date from Date Column

I have a SQLite Database where I am getting data from all columns based on a given date eg. 30 Sep 2018. Where in COL2 I am saving dates in the same format.
Cursor inc_con_by_dat(String dat) {
SQLiteDatabase db = this.getWritableDatabase();
String que = "SELECT * FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + dat + "'";
return db.rawQuery(que, null);
}
But now the COL2 Doesn't have the date format like 30 Sep 2018 anymore. cause I have decided to include data entry time in COL2 as well.
So I am saving COL2 in "EEE MMM dd HH:mm:ss Z yyyy" this format. But I am willing to change my "EEE MMM dd HH:mm:ss Z yyyy" format to anything that includes date and time. But I want to select columns only supplying like this example format "30 Sep 2018" or yyyy/mm/dd
So can anybody help me. or I just have to make another column for the time entry as well.
So I am saving COL2 in "EEE MMM dd HH:mm:ss Z yyyy" this format
Stop doing that. SQLite does not actually have a date column type, which means that your date information is being stored as literal text. Rather than trying to give you a workaround, I will just recommend that you always store your dates and timestamps in SQLite using an ISO format, something like:
YYYY-MM-DD HH:MI:SS
If you take this advice, then you would easily be able to compare another ISO date or timestamp against any record in your table. For example, if you wanted to find all records having a timestamp which fell on 2018-09-30, you could use this query:
SELECT *
FROM yourTable
WHERE ts >= '2018-09-30' AND ts < '2018-10-01';

How to fetch Records for a week

I am using Java 7 and fetching records for a week.For valid_from column I am subtracting -7 from current date below. The format of date in DB is 12-FEB-18. For valid_to column I am using sysdate. I am not getting correct valid_from date. Can anyone review this what is wrong here.
Format formatter = new SimpleDateFormat("dd-MMM-yy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
Date todate1 = cal.getTime();
Date startdate = ((DateFormat)formatter).parse(formatter.format(todate1));
System.out.println(todayWithZeroTime);
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM >"
+ startdate+ " and a.VALID_TO > sysdate";
How can I parse only Date here. Currently I am getting Tue Feb 13 00:00:00 GMT 2018. I want 13-FEB-18 which I can send as variable in where condition.
Please suggest
You are converting a Date to a String then back to a Date.
Then you are using this Date object in your query, so it's toString() method gets called and yields a String representation which is probably not the one you wanted.
Avoid the last conversion from String to Date and just use
String startdate = formatter.format(todate1);
Note that you also have to escape the date string with quotes :
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where "
+ "a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM > '"
+ startdate+ "' and a.VALID_TO > sysdate";
Also consider having a look at Java time API and at How to use PreparedStatement

SQL statement in Java to sort by date (month)

I have an SQL table in my Android project, that has a KEY_DATE field in Date format.
KEY_DATE + " DATE,"
My table is populated from the java code (date in dd/mm/yy format).
So now I need to make several date-related queries and something isn't working.
I need to make selections from a table for today, this month and this year.
Here's what I tried:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
Date todayD = new Date();
dateFormat.format(todayD);
String today = dateFormat.format(todayD);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
dateFormat.format(firstDay);
String selectQuery = "SELECT * FROM " + TABLE_PAYMENTS + "WHERE "
+ KEY_DATE +" BETWEEN " + firstDay + " AND " + today;
The query returns empty even though there's a lot of data for that period.
I believe something is wrong with data formats here. Can you help me to solve this?
Thank you in advance.
You are not formatting firstD, so you only get from the first day of the month at the current time on;
You should either use single quotes around the dates in your queries or use prepared statements, otherwise your server will understand your dates as math operations;
When querying for date ranges, remember that if you don't specify an hour with your date SQL will by default take it as zero hour (0:00:00.0000). If you use "between startDate and today", you get only midnight of today. If you use "between startDate and tomorrow", you get midnight of tomorrow too. You should use "date >= startDate and date < tomorrow" to get the proper range.
When writing queries with dates, I always prefer to use ISO format for the date strings: yyyy-MM-dd.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date todayD = new Date();
cal.setTime(todayD);
cal.add(Calendar.DATE, 1);
Date tomorrowD = cal.getTime();
String today = dateFormat.format(tomorrowD);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstD = cal.getTime();
String firstDay = dateFormat.format(firstD);
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE KEY_DATE >= '" + firstDay + "' AND KEY_DATE < '" + today + "'";
The problem is with the date formats for the data present inside the database and the date formats that you are passing (strings) to the sql query.
It is not a good practice to pass dates as string parameters to the sql query, so I strongly suggest use preparedStatement as shown below:
Date todayD = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE BETWEEN ? AND ?" ;
//create preparedStatement here
preparedStatement.setDate(1, firstDay);
preparedStatement.setDate(2, todayD);

JDBC date to SQL date

I have been using Java to store some records from a csv file.
One of these records is a date. The problem here is I am using JDBC to store these records in a database. Now, the Date object of Java is showing an error while putting it into the database. I have been stuck on this for a while. Please let me know how to solve this. I have used type Date in mysql for storing it into the database. Here is the part creating the problem.
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
"VALUES("+"DATE_FORMAT("+d+","+"'%Y-%m-%d'"+"))";
stmt.executeUpdate(sql);
If I execute this directly in MySqlWorkBench, it is storing the date properly. But through JDBC it is a problem.
The error is as shown below :
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Jun 30 14:04:03 IST 2016,'%Y-%m-%d'))' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1402)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1317)
at payex.writeDB(payex.java:221)
at payextestdrive.main(payextestdrive.java:11)
You add d.toString() to the SQL command when you want to add the formatted date string. Also a space is missing between the table name and VALUES:
String sql = "INSERT INTO TESTING VALUES(DATE_FORMAT(" + d1.format(d) +",'%Y-%m-%d'))";
The error message is pretty clear
right syntax to use near 'Jun 30 14:04:03 IST 2016,'%Y-%m-%d'))'
The format you provided is MMM DD HH:mm:ss Z YYYY, but the system expects %Y-%m-%d
Try
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
" VALUES("+"DATE_FORMAT('"+d1.format(d)+"',"+"'%Y-%m-%d'"+"))";
stmt.executeUpdate(sql);
or simply
DateFormat d1 = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
System.out.println(d1.format(d));
String sql = "INSERT INTO TESTING"+
" VALUES('"+d1.format(d)+"')";
stmt.executeUpdate(sql);

get relevent id for a date from the database

i tried to get the relevent id for the selected date in hibernate.but it returns 0 size list.but the date is exist in the data base.but i cant get the id for that date
transaction = session.beginTransaction();
Query query = session.createQuery(" FROM RoomRate WHERE currdate='" + date + "'");
List<RoomRate> list = (List<RoomRate>) query.list();
Have a look at these examples
http://www.mkyong.com/hibernate/hibernate-criteria-examples/
The key point being that the date needs to be formatted as in
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
and then you can query using
" where date >= '" + sdf.format(startDate) + "'"
BTW - why do you have a transaction and a commit on a select?

Categories

Resources