Oracle preparedstatement - date

I am trying to save this data into oracle datebase but (Member start Date and Member end date) giving an error i am using datepicker from JPallet for date and preparedstatemet allows me in pst.setString(6, startdate.getDate()); int or string. Please help me for solving this problem. I shall be very thankful to you.
Error Lines:
pst.setString(6, startdate.getDate());
pst.setString(7, enddate.getDate());
Full method:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
con = javadb.ConnectDb();
try{
String sql = "insert into membertable(id,name,membershipno,department,idno,"
+ "startdate,enddate,officeaddress,officephone,homeaddress,homephone,dateofbirth,"
+ "fieldofinterest,remarks) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pst = (OraclePreparedStatement) con.prepareStatement(sql);
pst.setString(1, null);
pst.setString(2, name.getText());
pst.setString(3, membershipno.getText());
pst.setString(4, department.getText());
pst.setString(5, idno.getText());
pst.setString(6, startdate.getDate());
pst.setString(7, enddate.getDate());
pst.setString(8, officeaddress.getText());
pst.setString(9, officephone.getText());
pst.setString(10, homeaddress.getText());
pst.setString(11, homephone.getText());
pst.setString(12, dateofbirth.getText());
pst.setString(13, fieldofinterest.getText());
pst.setString(14, remarks.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Book added successfully!");
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
update_table();
}
And date picker code is here
private void startdateActionPerformed(java.awt.event.ActionEvent evt) {
}
And this is not the textfield so therefore i am facing the problem. And i want to correct and also don't want to change it because it is front end reqiurement. Because user don't wants to insert date manually. Thanks.

When inserting a date, don't use pst.setString(). Instead, you should use pst.setDate() (this is really the whole point of using PreparedStatements in the first place). Because setString is inserting a date string with some unknown format. setDate tells the database to expect a date and there is no date format conversion necessary.
Also, to do this, you'll need to use a java.sql.Date instead of (what I'm assuming your palette is returning) a java.util.Date.
So this
pst.setString(6, startdate.getDate());
pst.setString(7, enddate.getDate());
should look like this
pst.setDate(6, new java.sql.Date(startdate.getDate().getTime()));
pst.setDate(7, new java.sql.Date(enddate.getDate().getTime()));

Related

how to increment 1 value in email address for uniqueness in selenium webdriver

I am writing test script for signup page and i need to put email address on each time. Can someone help me how to increment by value 1 in the email address as i execute the script for example, test#test.com and next time value should be test1#test.com. I an try with time stamp but not successfully work.
public class GetCurrentTimeStamp
{
public static void main( String[] args )
{
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
}
}
If you are trying to provide always unique email id, then you can use date with seconds as it keep changing also you can use
System.currentTimeMillis()
which gives number always unique. so you can append/concatenate it to email, i hope you know it.
You can use below code to get date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/04/19 16:05:48
depends of simple date format provide 'yyyy/MM/dd HH:mm:ss' output will be displayed.
Thank You,
Murali
Use java.util.Date class instead of Timestamp and format it like so.
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
String email= "test"+ timestamp + "#test.com";
Use below code:-
int num = 1; // Put this stament outside the for loop or put it as global variable.
Now use below code :-
num++;
String email= "test"+ num + "#test.com";
Hope it will help you :)

How to set Date Format in GXT RowEditing?

Straight to the problem.
I have a 6-columns grid, one of those 6 fields being a date.
While editing is enabled DateCell is not editable, as intended, but it changes its display format from "dd/mm/yyyy", as stated in ColumnConfig, to a non-specified anywhere full date format.
How to resolve this?
Obviously I can't treat dates as strings, as I thought at first, because I'm going to lose all the possible filtering on date.
Did you try something like that?
DateTimeFormat dtf = DateTimeFormat.getFormat("yyyyMMddHHmmss");
DateField df = new DateField();
df.setPropertyEditor(new DateTimePropertyEditor(dtf));
Cell c = new DateCell(DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss"));
grid.getColumnModel().getColumn(0).setCell(c);
editing.addEditor(df);
Hope it will help. It worked for me.
EDIT: Set column date format without making cell editable.
You should try that:
ColumnConfig<Plant, Date> date = editableGrid.getColumnModel().getColumn(3);
rowEditing.addRenderer(date, new AbstractSafeHtmlRenderer<Date>() {
#Override
public SafeHtml render(Date object) {
SafeHtmlBuilder builder = new SafeHtmlBuilder();
DateTimeFormat df = DateTimeFormat.getFormat("MM-dd-yyyy");
builder.appendHtmlConstant("<div qtip='" + Format.htmlEncode(object.toString()) + "'>" + df.format(object)
+ "</div>");
return builder.toSafeHtml();
}
});

date cannot be cast to fit into JDateChooser

Hello Guys I am facing problem with casting date that I retrieve from Ms access DB to JDateChooser, but a message appear to me telling java.util.Date cannot be cast to java.util.Date..
String sql="select * from Patient where PatientID=?"; try{
ps=con.prepareStatement(sql);
ps.setString(1, txt_PID.getText());
rs=ps.executeQuery();
if(rs.next()){
// String add1=rs.getString("PatientID");
// txt_PID.setText(add1);
String add2=rs.getString("PatientName");
txt_PName.setText(add2);
String add3=rs.getString("PatientGender");
cmb_PGender.setSelectedItem(add3);
String add4=rs.getString("PatientAge");
txt_PAge.setText(add4);
String add5=rs.getString("PatientType");
cmb_PType.setSelectedItem(add5);
String add6=rs.getString("PatientGSM");
txt_PGsm.setText(add6);
String add7=rs.getString("Patient_Maj_Jop");
txt_major_Jop.setText(add7);
DateFormat formatter ;
Date date1;
String add8=rs.getString("DateOfReg");
formatter = new SimpleDateFormat("MMM d, yyyy");
date1 = (Date)formatter.parse(add8);
dch_Date.setDate(date1);
table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} }catch(Exception e){ JOptionPane.showMessageDialog(null, e.getMessage());
}
if(txt_PID.getText().equals("")){
Update_Table();
}
Without looking at date1 variable, I'm guessing you might be using java.sql.Date? Check you are indeed using java.util.Date.
Show us your import statements.
The problem is with this line because DateFormatter is returning you an instance of java.util.Date and you are trying to cast it to a java.sql.Date which it isn't.
date1 = (Date)formatter.parse(add8);
Easy fix is to import java.util.Date instead. I don't see there is a need for you to use java.sql.Date as you are not fetching Date SQL colum, are you?

breezejs: date is not set to the right time

I've noticed that if a date property comes back from the server with the value "2013-07-11T17:11:04.700", then breeze changes the value to Thu Jul 11 19:11:04 UTC+0200 2013.
Notice the time is now 2 hours ahead !
I had already come across this issue when saving entities, so I had to explicitly convert my date properties using momentjs :
date.hours(date.hours() - moment().zone() / 60);
But now it seems the problem occurs also when doing read operations.
What's the best way to make sure breeze does not alter values of my date properties ?
Breeze does not manipulate the datetimes going to and from the server in any way EXCEPT to add a UTZ timezone specifier to any dates returned from the server that do not already have one. This is only done because different browsers interpret dates without a timezone specifier differently and we want consistency between browsers.
The source of your issues is likely to be that when you save your data with dates to the database, that the dateTime datatype you are using does NOT contain a timezone offset. This means that when the data is retrieved you are likely "losing" the offset and the Breeze default mentioned above kicks in. This can be corrected by using a database date time datatype with an timezone offset ( datetime2 or datetimeoffset in SQLServer).
Note that your browser DOES format dates according to it's current timezone.
Another approach is that you can replace Breeze's DataType.parseDateFromServer to NOT infer any time zone info if it is not provided:
breeze.DataType.parseDateFromServer = function (source) {
return new Date(Date.parse(source));
};
However, this can run into the problem that different browsers interpret DateTime strings without a time zone offset differently... So you may still get strange results depending on the browser. If that happens you will need to add some browser detection code to the snippet above.
Another alternative is to do the following using the moment.js library.
breeze.DataType.parseDateFromServer = function (source) {
var date = moment(source);
return date.toDate();
};
Not sure how helpful this is, but hopefully Breeze's behavior is clearer.
By default, Breeze does not provide any way to do this, but you can keep the below code in your model JS file to overcome this issue:
breeze.DataType.parseDateFromServer = function (source) {
if (typeof source === 'string') {
//Check for local offset time or UTC time from server
if (source.slice(-1) !== "Z") {
var oldSource = source;
try {
source = source.substring(0, source.lastIndexOf("-") - 1)
source = new Date(source);
var tzDifference = source.getTimezoneOffset();
//convert the offset to milliseconds, add to targetTime, and make a new Date
var offsetTime = new Date(source.getTime() + tzDifference * 60 * 1000);
return offsetTime;
}
catch (err) {
source = new Date(source);
return source;
}
}
else {
source = new Date(source);
var tzDifference = source.getTimezoneOffset();
//convert the offset to milliseconds, add to targetTime, and make a new Date
var offsetTime = new Date(source.getTime() + tzDifference * 60 * 1000);
return offsetTime;
}
}
}

Date browsers problem - if manually changed and focus on it - did not save

I have a problem related to Date type which I'm using in smartgwt.
I set up the date to have the possibility to change it manually:
setAttribute("useTextField", true);
In Firefox and Chrome (and maybe other browsers , except Internet Explorer) if first I'm selecting a date with that pop-up calendar and than change it manually and then let the focus on the date field and going to save the document (actually is a form with multiple fields) the date changed manually it is lost, the date choosed from calendar it is saved. This is not happening in Internet Explorer.
In all browsers, if I select from Calendar a date and than change it manually and change the focus from it everythings goes fine - the manually changed date it is saved into db.
Need some advices.
Thank you a lot.
Later edit:
I'm using com.smartgwt.client.widgets.form.fields.DateItem widget.
DateItem date = new DateItem("A date");
date.setWidth(320);
date.setWrapTitle(false);
date.setAttribute("useTextField", true);
date.setAttribute("inputFormat", "yyyy/MM/dd");
date.setAttribute("displayFormat", "toJapanShortDate");
I'm adding this date on a DynamicForm:
DynamicForm form = new DynamicForm();
form.setFields(date);
and this form on a VLayout object:
VLayout editLayout = new VLayout(30);
editLayout.addMember(form);
The problem is reproducing in browsers like Firefox & Chrome when:
I'm selecting first the date from calendar - say I'm selecting 2011/02/11
I'm changing the day in 2011/02/12 manually - and I'm not changing the focus from this date field
I'm pressing the 'Save' button.
After these steps the date is 2011/02/11 and not 2011/02/12 how it should be.
In Internet Explorer browser did not happen - the date after the steps above is 2011/02/12!
Later edit:
I'm using a DataSource for updating the data.
I'm having a UserObject and in the userUpdate method I'm creating this user object first with values from fields (which are on the DynamicForm) - by calling the generateUserObjectFromForm() method
UserObject user = generateUserObjectFromForm();
Here, in this method I'm doing something like:
user.setAddedDate(date.getValueAsDate()),
but here the date.getValueAsDate() value is the one selected from calendar, not the one modified manually.
I've tried also with:
date.getValue() //Fri Feb 11 00:00:00 GMT+200 2011
date.getValueField() // null
date.getValueAsDate() //Fri Feb 11 00:00:00 GMT+200 2011
date.getDisplayField() //null
date.getDisplayValue()//l2011/02/11
but none worked properly.
I'm using an request object (UserUpdateRequest) for updating the user.
UserUpdateRequest looks like:
public class UserUpdateRequest implements IsSerializable
{
UserObject user = null;
public UserUpdateRequest ()
{
}
public UserUpdateRequest (UserObject user)
{
this.user = user;
}
public UserObject getUser ()
{
return user;
}
}
final UserUpdateRequest request = new UserUpdateRequest(user);
and on the RPC user update method I'm sending this UserUpdateRequest request.
Later edit (15 february):
I've discovered why is happening this issue related to focus, and this is because in the project I'm not using a Button object - and a com.google.gwt.event.dom.client.ClickEvent for it. I'm using a personalized widget:
package de.vogella.gwt.helloworld.client;
import com.smartgwt.client.widgets.Label;
public class buttonLabel extends Label
{
public buttonLabel (String text, String elementID)
{
super();
setContents(text);
setAutoWidth();
setBaseStyle("wwHoverLabel");
setShowRollOver(true);
}
}
and this use com.smartgwt.client.widgets.events.ClickHandler().
Anyway I do not know how to resolve this ....
I've created a small project with this issue where I've put also a Button object (Save1) and also a personalized button buttonLabel (Save2) - both with clickhandlers.
Here is the link where you can download sources of this small project I've created: link
Case1:
say for example we choose date 2011/02/16 and we change manually the date into 2011/02/17 and push the button Save1 - everything works fine - the date remains 2011/02/17
Case2-a - line
Window.alert("2 " + date.getValue()); un-commented:
say for example we choose date 2011/02/16 and we change manually the date into 2011/02/17 and push the button Save2 - in the warning message date value is 2011/02/16 but in the field date remains 2011/02/17
Case2-b - line
Window.alert("2 " + date.getValue()); uncommented:
say for example we choose date 2011/02/16 and we change manually the date into 2011/02/17 and push the button Save2 - the value from field date is automatically changed to 2011/02/16
Later later edit:
Since I can't figure out how to solve my problem I'm thinking for the moment at a temporary solution.
So, I have:
DateItem date = new DateItem("Adate");
date.setWidth(120);
date.setWrapTitle(false);
date.setAttribute("useTextField", true);
date.setAttribute("inputFormat", "yyyy/MM/dd");
date.setAttribute("displayFormat", "toJapanShortDate");
Because the attribute useTextField is set to true we can see the text entry field. How can I make this text entry field to be un-editable. Actually I want to have only the possibility to choose the date from calendar and not to change it manually.
The following code should work.
DateItem date = new DateItem("Adate");
date.setAttribute("useTextField", true);
date.setAttribute("inputFormat", "yyyy/MM/dd");
date.setAttribute("displayFormat", "toJapanShortDate");
TextItem textItem = new TextItem();
textItem.setAttribute("readOnly", "true");
date.setTextFieldProperties(textItem);