Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL INSERT system date into table

Tags:

java

sql

I have created a table called "myTable" with a column called CURRENT_DATE and it's data type is "DATE". When I programatically update my table, I also want to place a timestamp or system date in the CURRENT_DATE field. A portion of what I am doing is shown below, but it is not working. I would think this would be easy, but... Can you help?

//System date is captured for placement in the CURRENT_DATE field in myTable
 java.util.Date currentDate = new java.util.Date();
...
stmt.executeQuery("INSERT INTO myTable (NAME, CURRENT_DATE) VALUES (' " + userName + " ', ' " + currentDate + " ')  ");      
like image 296
lakshmi Avatar asked Jul 12 '10 06:07

lakshmi


People also ask

How do you add a Sysdate to a table?

(to_date(sysdate, 'yyyy/mm/dd hh24:mi:ss')); The value is inserted as 08-02-12 12:00:00. In this query, it always stores the default time as 12 a.m.

How do I insert a Sysdate into a column?

To insert a SYSDATE value in Oracle, you can just insert the SYSDATE function into a DATE column. This is the ideal method because both the SYSDATE and the DATE column are in a date datatype. There's no need to convert when inserting into the table.

How do I create an automatic date in SQL?

You can use now() with default auto fill and current date and time for this. Later, you can extract the date part using date() function. Let us set the default value with some date.


3 Answers

You really should be doing this as a prepared statement using parameters, it makes things a lot easier and cuts out a few very simple SQL injection threats.

Connection con = ...;
PreparedStatement statement = con.prepareStatement("INSERT INTO myTable (NAME, CURRENT_DATE) VALUES ( ?, ?)");
statement.setString(1, userName);
statement.setDate(2, currentDate );
statement.execute();

There is plenty of info on how to use prepared statements properly. For example: http://www.jdbc-tutorial.com/jdbc-prepared-statements.htm

like image 89
Dunderklumpen Avatar answered Oct 20 '22 08:10

Dunderklumpen


If you just want the current date, you can retrieve that from the SQL server, without submitting it as a variable. It varies a little depending on what server you're using, but in MS SQL Server there's a function called getdate().

stmt.executeQuery("INSERT INTO myTable (NAME, CURRENT_DATE) VALUES (' " + userName + " ', getdate()");      

You can also set getdate() as the default value for that field, so that you can omit the field entirely:

stmt.executeQuery("INSERT INTO myTable (NAME) VALUES (' " + userName + " '" ')  ");      
like image 27
David Hedlund Avatar answered Oct 20 '22 08:10

David Hedlund


Don't put strings in the SQL. Use a prepared statement and set parameters.

like image 39
onof Avatar answered Oct 20 '22 08:10

onof