Reputation: 11
I have just created a simple Student Registration Form using Java(Netbeans). It has several columns to enter the students' data such as regNo, name, address, etc and a Insert button which inserts the data into the table created in MS Access.It works fine.But I need to store the time when a user fills that form.It means when a user fills that form, the system time should be captured and stored in the table for each entry(each tuple). So I want to know how to get the system time and insert into MS Access database.I found the following code.But I don't know how to pass the time captured by the code to the database.I have already created the field for enter the time in the database.
Calendar cal = Calendar.getInstance();
java.util.Date currentTime = cal.getTime();
This is the code I wrote to pass time to the table.....
ps = con.prepareStatement("insert into RegInfo(RegNo,StudName,Address,"
+ "Telephone,Stream,RegDate,Time) values(?,?,?,?,?,?,?)");
ps.setLong(6,currentTime.getTime());
I used your code Razvan. It is working really good but it doesn't insert the Time into the table......("System.out.println" is working properly).....
final String t1 = "hh:mm:ss";
final DateFormat df = new SimpleDateFormat(t1);
final String formattedTime = df.format(new java.util.Date());
ps.setString(7, formattedTime);
System.out.println("formattedTime "+formattedTime);
Upvotes: 1
Views: 1129
Reputation: 123809
You can simply use the Now()
function in your INSERT query:
try (Connection conn = DriverManager.getConnection(connStr)) {
String sql;
sql = "INSERT INTO RegInfo (RegNo, StudName, Address, Telephone, Stream, RegDateTime) " +
"VALUES (?, ?, ?, ?, ?, Now())";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 3);
ps.setString(2, "Gord");
ps.setString(3, "123 Main St");
ps.setString(4, "416-555-1212");
ps.setString(5, "Standard");
ps.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
That will work for both JDBC-ODBC (obsolete, removed from Java 8) and UCanAccess (more info here).
Note that Date/Time columns in Access always have both a Date and Time component, so you don't need to maintain separate columns for RegDate
and Time
.
Upvotes: 1
Reputation: 1009
your time is not the first column in the insert statement it is number 6 so just change your ps parameter as ps.setLong(6,currentTime.getTime());
Upvotes: 0
Reputation: 434
The generic form could be :
final String DB_DATE_FORMAT = "MM/dd/YYYY"; //not sure about this, modify to fit your Access date format
final SimpleDateFormat formatter = new SimpleDateFormat(DB_DATE_FORMAT);
final String formattedDate = formatter.format(new Date());
Upvotes: 0