java.util.Date date = new java.util.Date();
java.sql.Date today = new java.sql.Date(date.getTime()); //2012-03-23
java.sql.Time time = new java.sql.Time(date.getTime()); //02:32:46
PreparedStatement pst = null;
String queryString = "INSERT INTO PR_VISITOR(PRISONER_ID,VISITOR_NAME,FATHER_NAME,DOV,IN_TIME) VALUES (?,?,?,?,?)";
pst = connect.prepareStatement(queryString);
pst.setString(1, pr_id);
pst.setString(2, visit);
pst.setString(3, father);
pst.setDate(4, today);
pst.setTime(5, time);
int officerQuery = pst.executeUpdate();
if (officerQuery == 1) {
response.sendRedirect("/FYP3.4/prisonAdmin/visitor_out.jsp");
JOptionPane.showMessageDialog(null, "Visitor information registered !!", "Visitor Information", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Unable to Add information !!", "Visitor Information", JOptionPane.ERROR_MESSAGE);
}
By using the above code i'm trying to insert the current date and time into table,which have the separate columns. When i'm executing the above query then it insert the todays date in the time IN_TIME field too.
EDIT
DATATYPE OF IN_TIME and DOV are DATE .
Need Help.. !!
Since DOV and IN_TIME is date you don't need to separate date and hour. The type date in Oracle holds date and time. I suggest you change your table to have just one date column.
To insert the current time you can use the Oracle's sysdate function:
INSERT INTO PR_VISITOR(PRISONER_ID,VISITOR_NAME,FATHER_NAME,DATETIME_COLUMN) VALUES (?,?,?,?,SYSDATE)
To format your output of the date value you can use the SimpleDateFormat class in Java or to_char in Oracle.
A DATE column in an Oracle database will always store both a day (i.e. March 22, 2012) and a time to the second (i.e. 3:30:00 PM). A java.sql.Date and a java.sql.Time store the day and time as well but to the millisecond.
It doesn't really make sense to have separate columns in Oracle for the day and for the time but particularly not where both columns are declared as DATE data types. It would be much more conventional to use a single column declared as a DATE. If you really wanted to, you could truncate the day so that it represents midnight on the current day and then store the time component as, say, an INTERVAL DAY TO SECOND. But that would generally add a fair amount of complexity to the system for very little gain.
You're much better off using oracle's 'systimestamp'. The reason being, if you're java code is running in one timezone, and oracle lives in another. Forcing your own Time object, could cause problems.
Do you really need separate fields for this? I would think just having a timestamp would be enough.
Use SimpleDateFormat. This is one way I have used it:
Date now = Calendar.getInstance().getTime());
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String date = df.format(now);
DateFormat tf = new SimpleDateFormat("HHmmss");
String time = tf.format(now);
Follow this,it will help both in java and oracle
create table datetime(date_time timestamp);
insert into datetime values (sysdate);
To get date:
select to_char(date_time,'DD-MON-YY') from datetime;
eg:12-JUL-12
To get month:
select to_char(date_time,'mm') from datetime;
eg:7
To get time:
select to_char(date_time,'HH24:MI:SS') from datetime;
eg:23:56:15
cheers!!
Related
i tried to store in two column current data and time on my microsft access database from java, but when i open my file no data has been stored. I tried to print the columns but it print "null".
How can i do?
Date date = new Date();
final String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(date.getTime());
final String formattedTime = new SimpleDateFormat("HH:mm:ss").format(date.getTime());
final java.sql.Date sqlDate = java.sql.Date.valueOf(formattedDate);
final java.sql.Time sqlTime = java.sql.Time.valueOf(formattedTime);
...
PreparedStatement ps=con.prepareStatement("insert into Table1(Data) values(?)");
ps.setDate(1,sqlDate);
ps=con.prepareStatement("insert into Table1(Hour) values(?)");
ps.setTime(1,sqlTime);
ps.executeUpdate();
This is the printed result :
ID Name Date Hour
0001 Mary null null
A couple of points:
As far as I can tell, there is no point in keeping your date and your time in two separate columns in your database table. I would use one column of datatype datetime.
The classes java.util.Date, SimpleDateFormat, java.sql.Date and Time are long outdated and poorly designed. Better to use java.time, the modern Java date and time API. It is so much nicer to work with.
Taking for granted that date and time are in separate columns your code may look like this:
LocalDateTime dateTimeNow = LocalDateTime.now(ZoneId.of("Europe/Rome"));
LocalDate dateToday = dateTimeNow.toLocalDate();
LocalTime timeNow = dateTimeNow.toLocalTime();
PreparedStatement ps
= con.prepareStatement("insert into Table1(Data, Hour) values(?, ?)");
ps.setObject(1, dateToday);
ps.setObject(2, timeNow);
ps.executeUpdate();
This will insert one row containing both the current day and the current time. Please use your desired time zone where I put Europe/Rome since both date and time depend on time zone.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I have a Sqlite3 database table contains name,address,date of birth details.i want to display 1990-01-01 to 1995-01-01 details.
but Sqlite3 database stores only following data types.
TEXT
NUMERIC
INTEGER
REAL
NONE
Any one have some hint to store and retrieve date format data..?
From my own experience on doing several projects with database in Android my answer is:
Do not store the date as a string. Never! Ever! Store them as Unix timestamps and format them as needed during runtime.
the important thing here is to separate what is your data and what is the on-screen representation of your data. Storing in a database the on-screen representation of your data is wrong.
You'll always store your dates as INTEGER types.
So for example to store the date now you'll store the value System.currentTimeInMilis
To select between 1990-01-01 and 1995-01-01 you will:
long val1 = new GregorianCalendar(1990, 01, 01).getTimeInMillis();
long val2 = new GregorianCalendar(1995, 01, 01).getTimeInMillis();
and then you'll do the normal SELECT statement between those 2 values.
to show those values in the screen as yyyy-MM-dd you'll use the SimpleDateFormat class:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
long longDate = cursor.getLong(colNumber); // from the database
String stringDate = dateFormat.format(new Date(longDate));
Use this code to convert your date into millisecond format and store it into your database as INTEGER types
String someDate = "1995-01-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(someDate);
System.out.println(date.getTime());
date.getTime()-give the millisecond format
At the same way to convert your input (i.e from 1990-01-01 and to date 1995-01-01)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse(1990-01-01);
value1=date.getTime();
Date date2 = sdf.parse(1995-01-01);
value2=date.getTime();
Retrieve from database using following query
db.rawQuery("SELECT * FROM table_name WHERE column_name BETWEEN "+value1+" AND "+value2+"",null);
or
db.rawQuery("SELECT * FROM table_name WHERE column_name<="+value1+" AND column_name>="+value2+"",null);
You can do something like this
DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
Date date1=df.parse("1990-01-01");
Date date2=df.parse("1995-01-01");
Date myDate=df.parse("1992-01-01"); // checking date
if((date1.getTime()<myDate.getTime())&&(myDate.getTime()<date2.getTime())){
System.out.println(df.format(myDate)+" is in this range");
}else{
System.out.println(df.format(myDate)+" is not in this range");
}
Since the format you want to use (yyyy-MM-dd) is ordered in the same way as a String (i.e. for any dates x and y you would choose, if x < y as a Date, then x < y as a String), you can simply store the dates as Strings (TEXT) in your database.
When selecting the values between them, you would just have to use a WHERE clause in your SELECT statement like this:
SELECT * FROM yourTable WHERE yourDateFieldName > ? and yourDateFieldName < ?
You can then use DateFormat.format to set the values for the ? parameters of your prepared statement. The first parameter would be the "start" date, and the second would be the "end" date. You can replace < with <= and > with >= if you want the items on start and end dates included.
This gives you a String representation of a Date. To convert from that to an actual Date object you can use date formatter's parse method (i.e. SimpleDateFormat.parse).
Another, "cleaner", approach would be to use the SQLite date and time functions (see here). While SQLite doesn't have a DATE type for storing date values, it has helper functions that you can use to interpret TEXT and NUMBER values as date in your statements.
If you don't need extra processing for your date values, I'd recommend going for the first solution as it should be faster because it merely compares TEXTs rather than parsing and extracting a date from them, then comparing the extracted date (I haven't compared the speed of the two approaches, so don't take my word for it on this one). This approach also has less code to write and maintain and the code is easier to read.
Sources:
SQLite data type - for the validity of comparing two TEXT values
SimpleDateFormat - Android documentation
You can use dates in yyyy-MM-dd format directly, JDBC will understand it. Assuming we a have a table t1 with c1 of DATE type
PreparedStatement ps = conn.prepareStatement("insert into t1 (c1) values (?)");
ps.setString(1, "2001-01-01");
ps.executeUpdate();
Reading dates is simple too
ResultSet rs = st.executeQuery("select c1 from t1");
rs.next();
Date date = rs.getDate(1);
ResultSet.getDate returns result as java.sql.Date whose toString method returns date in yyyy-MM-dd format
I have a column in my table from type datetime, I am retrieve that column to my java application using jdbc.
my problem is that when I stored 2014-05-13 23:49:18.150 in my database, it becomes 2014-04-13 in my java application.
how to get all the date include time (house, seconds , minutes ).
java code
callableStatement = con
.prepareCall("{call getStatusForOrder(?,?,?,?,?)}");
callableStatement.setInt(1, order.getID());
callableStatement.registerOutParameter(2, java.sql.Types.INTEGER);
callableStatement.registerOutParameter(3, java.sql.Types.DATE);
callableStatement.registerOutParameter(4, java.sql.Types.DATE);
callableStatement.registerOutParameter(5, java.sql.Types.BIT);
callableStatement.execute();
int statusID = callableStatement.getInt(2);
Date startTime = callableStatement.getDate(3);
Date endTime = callableStatement.getDate(4);
boolean isActive = callableStatement.getBoolean(5);
System.out.println("IsActive = " + isActive);
System.out.println("Start Date = " + startTime.toString());
Use the Timestamp instead of Date, both datetime and datetime2 map to java.sql.Timestamp.
See the documentation.
PS. Do not forget to use callableStatement.getTimestamp instead of callableStatement.getDate.
http://docs.oracle.com/javase/6/docs/api/java/sql/CallableStatement.html#getTimestamp(int)
Use a DateFormat to display it.
SHORT is completely numeric, such as 12.13.52 or 3:30pm
MEDIUM is longer, such as Jan 12, 1952
LONG is longer, such as January 12, 1952 or 3:30:32pm
FULL is pretty completely specified, such as Tuesday, April 12, 1952 AD or 3:30:42pm PST.
I think you must use Timestamp (if I recall it right, haven't programmed Java for a while) instead of Date
Types.DATE signifies a JDBC (and SQL) datatype that only has a date component, and no time. You need to use Types.TIMESTAMP and the associated get/setTimestamp(..) methods and class java.sql.Timestamp if you want to have the time portion included.
I am looking for a way to get today's date and pass to sql table and save there. Call the saved date and do some task with JODA TIME API. The changed Joda time Date to sql table and save there and process continues..
I tried this way,
//prints todays date
java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
//passes wrong date to the table like 1970-07-01 instead of 2013-03-01
String insert = "INSERT INTO TEST_TABLE VALUES(1,"+sqlDate+")";
pStmt = conn.prepareStatement(insert);
pStmt.executeUpdate();
//converting to joda time
LocalDate ld = new LocalDate(sqlDate);
//some calculations, and how to convert back to sql date?
What I am trying to do here is, A table with 3 columns (id, startdate, finishdate). id will be entered by user, start date should be automatically entered todays date. after some calculations with joda time and finish date will be set to date it is finished.
Code
String insert = "INSERT INTO TEST_TABLE VALUES(2,'"+timestamp+"')";
Error
Data type mismatch in criteria expression
//I have created table using MS access
//the format of the date column is Date/Time.
You Can use Timestamp here. java.sql.Timestamp extends java.util.Date, so anything you can do with a java.util.Date you can also do with a java.sql.Timestamp.
To convert LocalDateTime to Timestamp
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
But if You still want to convert Timestamp into java.sql.Date then use this
java.sql.Date date = new java.sql.Date(timeStamp.getTime());
I am wanting to insert a datetime into a MySql data base using Java and a prepared statement:
Calendar cal = Calendar.getInstance();
PreparedStatement stmnt = db.PreparedStatement("INSERT INTO Run " +
"(Time) VALUE (?) ");
stmnt.setDate(1, new java.sql.Date(cal.getTime()));
stmnt.executeQuery();
NOTE: there is currently an error - cannot find symbol (java.sql.Date) line 4 here
db is an instance of a sort of wrapper class that exposes what I need from java.sql - its just getting a prepared statement from my connection object here.
Time (the column) is a date time in my database, and I can only see setDate and setTime method but I want to store both - also my code does not work anyway ;-)
If anyone could give me some pointers on inserting a combined date time (current time would be a great help as that's my first goal) into a MySql DB using a prepared statement I would be very grateful.
Thanks
The constructor for java.sql.Date takes a long (milliseconds since 1970) java.sql.Date
To get milliseconds from a java.uitl.Calendar, you use cal.getTimeInMillis()
Your code would be:
Calendar cal = Calendar.getInstance();
PreparedStatement stmnt = db.PreparedStatement("INSERT INTO Run " + "(Time) VALUE (?) ");
stmnt.setDate(1, new java.sql.Date(cal.getTimeInMillis()));
stmnt.executeQuery();
the following code should allow you to insert a date with millisecond accuracy. I have used it with HSQLDB, Sybase, SQL-Server and MySql without any problems.
java.util.Date date = getMyDate();
if (date == null) {
statement.setNull(insertionIndex, Types.TIMESTAMP);
} else {
statement.setTimestamp(insertionIndex, new Timestamp (date.getTime()));
}