简体   繁体   中英

insert date value into oracle using java not working

I'm trying to insert date format into Oracle from Java EE Eclipes. I'm able to insert a null value but not date value. The date prints out in the console okay but does not update the database. Here are my queries:

Inserting Date value: (NOT WORKING) Console output for uDate = 20/Sep/16

public void updateUnsubscribe(String empid) { 
  DateFormat df = new SimpleDateFormat("dd/MMM/yy");
  String uDate = df.format(new Date());
  String unSub = "udate MYDB set edate ='" + uDate + '" where emp = "empid"';
}

Inserting NULL value: (WORKING) Console output for uDate = null

public void updateSubscribe(String empid) { 
  Date toNull = null;
  String sub = "udate MYDB set edate ='" + toNull + '" where emp = "empid"';
}

I don't get any errors, at all, the only issue is the date field not inserting the date. What am I missing? Am I not formatting my date field correctly.

You could use oracle to_date function to convert varchar to date value, for your example:

public void updateUnsubscribe(String empid) { 
  DateFormat df = new SimpleDateFormat("dd/MM/yy");
  String uDate = df.format(new Date());
  String unSub = "udate MYDB set edate =to_date('" + uDate + ', 'dd/MM/yyyy')" where emp = "empid"';
}

But rather that, it is better to use JDBC PreparedStatement for this task:

public void updateUnsubscribe(String empid) { 
  PreparedStatement ps = conn.prepareStatement("update MYDB set edate=? where emp=?");
  ps.setTimestamp(1, new java.sql.Timestamp(new Date()));
  ps.setString(2, empid);
  ps.executeUpdate();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM