Getting java sql time and inserting it to a table - java

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.

Related

insert current date in oracle database using jdbc

I am trying to insert current date into Oracle sql.I had set the datatype to be DATE in oracle sql and changed the date format to DD-MM-YYYY.Now I am trying to insert current date as follows.But I am getting some error as shown below.Don't know what is wrong
String sql6 = "insert into account(acc_no,acc_type,primary_phone_number,people_in_plan,acc_activated_date,acc_deactivated_date) values('"+n1+"','"+acctype+"','"+primaryphoneno+"','"+number_of_people+"',?,?)";
Stmt = connection.prepareStatement(sql6);
SimpleDateFormat sdf=new SimpleDateFormat("DD-MM-YYYY");
Date date1 = new Date(System.currentTimeMillis());
Stmt.setString(5, sdf.format(date1));
Stmt.setNull(6, java.sql.Types.DATE);
Stmt.executeUpdate();
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.java:5386)
at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5374)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setString(OraclePreparedStatementWrapper.java:282)
It looks like your column indexes are incorrect. They should be 1 and 2 respective.
Stmt.setString(1, sdf.format(date1));
Stmt.setNull(2, java.sql.Types.DATE);
please user statement.setObject(1, new java.sql.Date());instead

sql delete based on date

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"));

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.

how to format date and time from JDateChooser to mysql datetime column

I am trying yo store current date and time from JDateChooser to mysql database, but it inserts only todays date and current time is 00:00:00
java.util.Date dt1,dt2;
String n=name.getText();
String i=id.getText();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
dt1=jDateChooser1.getDate();
dt2=jDateChooser2.getDate();
String strdtver1=(String) sdf.format(jDateChooser1.getDate());
String strdtver2=(String) sdf.format(jDateChooser2.getDate());
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
Statement stmt=con.createStatement();
String sql="Insert into ss values('"+(n)+"','"+(strdtver1)+"','"+(strdtver2)+"','"+(i)+"');";
stmt.executeUpdate(sql);
JOptionPane.showMessageDialog(this, "RECORD ENTERED SUCCESSFULLY");
} catch(Exception e) {
JOptionPane.showMessageDialog(this,e.getMessage());
}
It is a program to store check in & check out date and time.
The datatype in mysql is datetime for Check_in and Check_out.
The data entered in my sql at column Check_in is 2014-10-27 00:00:00. The current date is correct but i want to insert current time instead of 00:00:00.Please help me.
Your are formatting the dates you get from widgets using SimpleDateFormat, but you only use a date pattern as a format string; for date and time string format supported by mysql, use:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
You should not convert your Date objects to Strings. Instead, pass them to a PreparedStatement:
try (PreparedStatement statement =
con.prepareStatement("insert into ss values ?, ?, ?, ?")) {
statement.setString(1, n);
statement.setDate(2, dt1);
statement.setDate(3, dt2);
statement.setString(4, i);
statement.executeUpdate();
}
Also, using a PreparedStatement is highly recommended when storing user data, as it prevents a serious malicious attack vector known as SQL Injection. (Imagine if the user entered his name as ', null, null, null; delete from ss; insert '.)
public void calendarExpale(){
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
final JTextField textField = new JTextField(15);
JDateChooser chooser = new JDateChooser();
Date d1=(Date)chooser.getDate();
chooser.setSize(15, 10);
chooser.addPropertyChangeListener("date", new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
JDateChooser chooser = (JDateChooser)evt.getSource();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:MM:SS");
textField.setText(formatter.format(chooser.getDate()));
}
});
content.add(textField);
content.add(chooser);
}
This is the easiest way I have ever used. You do not need to do any extra thing .
statement.setString(2,((JTextField) jDateChooser1.getDateEditor().getUiComponent()).getText());

inserting html5 datepicker into oracle getting exceptions

i am trying to insert html5 datepicker's date into Oracle table having datatype date,i've tried so many thing but i am still facing problem,plz help me to solve the issue.
static int addNotification(String date,String message)
{
int i=0;
try {
ps=con.prepareStatement("INSERT into ev values(?,to_date(?,'DD-MON-YYYY'))");
ps.setString(1, message);
DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dt = originalFormat.parse(date);
String formattedDate = targetFormat.format(dt);
System.out.println(formattedDate);
ps.setString(2, formattedDate);
// ps.setDate(2,formattedDate);
i=ps.executeUpdate();
}
everytime i am making changes , i am getting new exception for ex.
java.sql.SQLException: ORA-01861: literal does not match format string
java.text.ParseException: Unparseable date('YYYY-MM-DD')
plz help me to solve this problem.
You can use PreparedStatement.setDate(int parameterIndex,Date x) as follows.
try {
ps=con.prepareStatement("INSERT into ev values(?,?)");
ps.setString(1, message);
DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
java.util.Date dt = originalFormat.parse(date);
ps.setDate(2,dt);
i=ps.executeUpdate();
}
if you want to convert the date then use,
DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
if not would suggest you not capture html 5 datepickers data directly ,I would rather convert it using javascript and send it to response.
go through date class :-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Categories