sql delete based on date - java

I am a total noob to java and sqlite. This should be simple, but I have tried and searched and can't get it to work. I have a date field in SQL that I am formatting as a sql date (MM/dd/yy). I want to delete based on a date passed. For the moment, I am only trying to display rows based on a passed date.
My code to run the query is:
String query = "select * from Peter1Score where DateSort='"+convertSQLDate("09/20/15")+"'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
My converSQLDate() is:
public static java.sql.Date convertSQLDate (String sqlDateIn)
{
java.sql.Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
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 passing 09/20/15 just for test. I have a record with that date, but it doesn't get selected.

You're not binding any variables into the statement (using the setXY() methods of PreparedStatement). Instead, you're concatenating a string value (result of Date.toString()) into the query literal.
Try this instead:
String query = "select * from Peter1Score where DateSort=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setDate(1, convertSQLDate("09/20/15"));

Related

How to create SQL date object in a desired format ( MM/DD/YYYY HH:MM:SS AM ) in Java?

In the database server, the format of the date column is MM/DD/YYYY HH:MM:SS AM
How can I create the SQL date object to send to database in the same format mentioned above?
Type of the database column is DATE. I am using Oracle Database 12C : SQL.
DATE or TIMESTAMP columns do not have "a format".
As your value apparently contains a time, you should use LocalDateTime or java.sql.Timestamp to retrieve that value.
Something like:
String sql = "select the_timstamp_column from the_table";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
LocalDateTime tsValue = rs.getObject(1, LocalDateTime.class);
}
But still not all JDBC drivers support that, so the second best solution is to use java.sql.Timestamp:
String sql = "select the_timstamp_column from the_table";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
java.sql.Timestamp tsValue = rs.getTimestamp(1);
}
In both cases you can format the value of tsValue anyway you like in your Java code.

Get a date from resultset that is already in localdate format?

My SQLlite database uses the format yyyy-mm-dd for dates. When I get a resulset from my database, I want to store the day of birth I got from my database by using a method from a different class. However, i'm not sure how to store it.
public void setBirthDay(LocalDate birthDay) {
this.birthDay = birthDay;
}
try (PreparedStatement stmt = conn.prepareStatement(
"select id, naam, voornaam, birthday, opmerking, debetstand_limiet, actief from klant where id = ?");) {
stmt.setInt(1, id);
stmt.execute();
try (ResultSet r = stmt.getResultSet()) {
Klant k = new Klant();
if (r.next()) {
k.setBirthDay(r.getDate("birthday").toLocalDate());
}
This is what I'm trying now, but is this even correct? The format is in LocalDate already, so why would i have to change it to LocalDate still? What is correct to do in this scenario?
String theOtherDay = "2011-07-12";
LocalDate today = LocalDate.now();
LocalDate tod = LocalDate.parse(theOtherDay);
System.out.println(today.toString());
System.out.println(tod.toString());
//2016-07-19
//2011-07-12
you can store the LocalDates objects in an arrayList if need be.

Using text field to retrieve date from excel

The error here shows that the data type criteria mismatch
Please tell how to filter the date using two text fields
The error at dateFormat = new SimpleDateFormat("dd/MM/YYYY").parse(G); shows that no method found for parse (Date)
String a=jTextField1.getText();
String b=jTextField2.getText();
Date n=new Date();
SimpleDateFormat date = new SimpleDateFormat("dd/MM/YYYY");
DefaultTableModel tm=(DefaultTableModel)jTable1.getModel();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection ("jdbc:odbc:NAMT","Navi","1234");
PreparedStatement ps=con.prepareStatement(
"select * from [Sheet1$] where SEVERITY='Critical' and DATE BETWEEN '"+a+"'and'"+b+"'" );
try (ResultSet rs =ps.executeQuery())
{
while(rs.next())
{
String B=rs.getString("NetworkElement");
String E=rs.getString("Severity");
java.util.Date G = rs.getDate("DATE");
java.util.Date dateFormat;
dateFormat = new SimpleDateFormat("dd/MM/YYYY").parse(G);
tm.addRow(new Object[] {B,E,G});
}
}
con.close();
}
catch(Exception x)
{
System.out.println(x);
}
SimpleDateFormat.parse()
expects a String, not a Date.
SimpleDateFormat.fomat()
takes a Date-Object.

Getting java sql time and inserting it to a table

Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Time currentTimestamp = new java.sql.Time(now.getTime());
Date date = new Date(currentTimestamp.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(date);
java.sql.Date.valueOf(formattedDate);
System.out.println(formattedDate);
How to get the current formatted System time(yyyy-MM-dd) and insert it to the table? I already tried my best and search for the answer but its no good I get different error messages like when I insert java.sql.Date.valueOf(formattedDate);I always get java.lang.IllegalArgumentException but when I remove java.sql.Date.valueOf(formattedDate) and change this line "+pcList.get(j).getid()+",0,0 into "+pcList.get(j).getid()+",0,2014-07-07 I always get an error saying Data truncation: Incorrect date value: '2000' for column 'date' at row 1
if(ifLoggedIn){
for(int j=0;j<b;j++){
try {
Connection conn = DriverManager.getConnection(url, "root", "");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(transactionID) from transaction");
while(rs.next()){
tID = rs.getInt("MAX(transactionID)");
}
tID= tID+1;
stmt.executeUpdate("Insert into ccpdb.transaction(membershipNum,productID,time,date,paymentOption,amount,transactionID,quantity) values ("+currentuser.getMembershipNum()+","+pcList.get(j).getid()+",0,0,\"west\","+tf1.getText()+","+tID+","+pcList.get(j).f3.getText()+")"
+ "");
conn.close();
} catch (Exception g) {
System.err.println("Got an exception! ");
System.err.println(g.getMessage());
}
}
}
Please help me!!
Just use the database time, rather than the java time. You can get it using the function now() or CURRENT_DATE. I can't quite tell where you want to put this in the insert, but it can go in the list of values.
Try this:
java.util.Date now = new java.util.Date();
java.sql.Date insertDate = new java.sql.Date(now.getTime());
You can insert this date directly.
You are getting this error as you are trying to save String in date column.

wrong value when converting String date to date Object

When I convert String date like "18/09/13,02:01:51"
Using this method:
public static Date stringToDateFormat(String dateString) {
Date date = null;
try {
date = new SimpleDateFormat("dd/MM/yy,hh:mm:ss").parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When I save this convert this date object to SQL Date and store it in PostgreSQL Database, I lose the time
2013-09-18 00:00:00
Here the DB insertion code"
String query = "INSERT INTO My_Table(my_date) VALUES (?)";
Date date = stringToDateFormat("18/09/13,02:01:51");
preparedStatement = connection.prepareStatement(query);
preparedStatement.setDate(1, new java.sql.Date(date.getTime()));
preparedStatement.executeUpdate();
Is it coding problem or DB configuration?
Thanks.
Your date string does not specify ms and is being rounded.
18/09/13,02:01:51 == 1379458917000
18/09/13,02:01:51.590 == 1379458917590
Update:
A format string which captures MS would be: dd/MM/yy,hh:mm:ss.SSS

Categories