2010-07-28 62 views
11

我用下面的代碼,但在SQL日期時間字段表示爲:如何使用SQL在數據庫中插入當前日期和時間?

2005-04-08 00:00:00 

我想有時間了。我應該改變什麼?

這裏是我下面的代碼:

// Get the system date and time. 
java.util.Date utilDate = new Date(); 
// Convert it to java.sql.Date 
java.sql.Date date = new java.sql.Date(utilDate.getTime()); 
... 
... 
... 
PreparedStatement stmt = connection.prepareStatement(sql); 
stmt.setDate(1, date); 
+1

在Microsoft SQL Server上,將當前日期插入到數據表最簡單的方法是將默認值添加到DateTime(或SmallDateTime)字段中:getdate() – 2010-07-28 08:00:20

回答

11

使用的setTimestamp代替的setDate,由於時間戳爲數據時間首選格式嘗試。

+3

java.sql.Date只支持dat呃,不是時間。 從javadoc - 「爲了符合SQL DATE的定義,由java.sql包裝的毫秒值。日期實例必須通過將實例關聯的特定時區中的小時,分​​鍾,秒和毫秒設置爲零來「標準化」。 – 2010-07-28 08:13:33

0

嘗試使用,而不是試圖設置SQL日期的setDate(utilDate)。 在SQL中,日期和時間是不同的數據類型。

2

試試這個:

Connection con; 
Statement stmt; 
con = DriverManager.getConnection(url, username, password); 
stmt = con.createStatement(); 
stmt.executeUpdate("INSERT INTO MYTABLE(time) " + 
"VALUES ('" + new java.sql.Date(System.CurrentTimeMillis())"');"); 
1

現在使用SQL函數()。

INSERT INTO table date_field VALUES(NOW()); 
-1

實際上,數據庫中的日期是像「yyyy-mm-dd」這樣的字符串。

爲什麼不嘗試:

String date = "2010-07-28";

stmt.executeUpdate("INSERT INTO MYTABLE(time) " + s);

這只是您想要的日期。

如果要立即插入,使用命令,如:

INSERT INTO MYTABLE(NOW());

4

你可以設置Timestamp import java.sql.Timestamp;

stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis())); 

代替

stmt.setDate(1, date); 

O/P將是:2014年5月16日08:34:52.977

設置你的數據庫--column的時間戳。

0

我沒有如下:

con = new BDConesion(); //Conexion with de DB 
Connection cn = con.conexion() 
PreparedStatement st = null; 
st = cn.prepareStatement("INSERT INTO TABLE (Id,Fecha,contendido) VALUES(?,?,?)"); 
st.setString(1,String.valueOf(key)); //convert the int to string 
st.setTimestamp(2, new Timestamp(System.currentTimeMillis())); 
st.setString(3,Cont);//Cont it is a varible string 
st.executeUpdate(); 

我希望你成爲

1

我不會理會檢索Java中的當前時間,就可以讓數據庫做的工作:

String sql = "insert into some_table (some_column, timestamp_column) values (?, current_timestamp)"; 
PreparedStatement stmt = connection.prepareStatement(sql); 
stmt.setInt(1, 42); 
stmt.executeUpdate(); 
相關問題