2013-01-22 54 views
2

如何使用JDBC在MS SQL 2005中插入datetime?我使用存儲過程在數據庫中插入:mssql 2005 datetime和jdbc

ALTER proc [dbo].[sp_insertid_report] 
@stream_time_gmt as datetime, 
@stream_time_local as datetime, 
@start_time_gmt as datetime, 
@end_time_gmt as datetime, 
@start_time_local as datetime, 
@end_time_local as datetime, 
@note_id as int, 
@reported_by as varchar(100), 
@date_reported as datetime, 
@date_created as datetime, 
@date_updated as datetime, 
@stream_id as int, 
@Fp_file_path as varchar(300), 
@Fp_name as varchar(200), 
@Is_Allowed as varchar(2) 

as 

begin 
insert into id_reports(stream_time_gmt,stream_time_local,start_time_gmt,end_time_gmt,start_time_local,end_time_local, 
note_id,reported_by,date_reported,date_created,date_updated,stream_id,Fp_file_path,Fp_name,Is_Allowed) 
values(@stream_time_gmt,@stream_time_local,@start_time_gmt,@end_time_gmt,@start_time_local, 
@end_time_local,@note_id,@reported_by,@date_reported,@date_created,@date_updated,@stream_id,@Fp_file_path,@Fp_name,@Is_Allowed) 
end 

我的JDBC代碼:

callableStatement = connection.prepareCall("{ call dbo.sp_insertid_report(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }"); 
     callableStatement.setDate(1, new Date(cvtToGmt(new java.util.Date(modifiedTime.toMillis())).getTime())); 
     callableStatement.setDate(2, new Date(modifiedTime.toMillis())); 
     callableStatement.setDate(3, new Date(cvtToGmt(startTime).getTime())); 
     callableStatement.setDate(4, new Date(cvtToGmt(endTime).getTime())); 
     callableStatement.setDate(5, new Date(endTime.getTime())); 
     callableStatement.setDate(6, new Date(endTime.getTime())); 
     callableStatement.setInt(7, songID); 
     callableStatement.setString(8, AudioMatcherService.hostName); 
     java.util.Date date = new java.util.Date(); 
     callableStatement.setDate(9, new Date(date.getTime())); 
     callableStatement.setDate(10, new Date(date.getTime())); 
     callableStatement.setDate(11, new Date(date.getTime())); 
     callableStatement.setInt(12, channel.getAssignmentID()); 
     callableStatement.setString(13, "no"); 
     callableStatement.setString(14, "no"); 
     callableStatement.setString(15, "Y"); 
     callableStatement.execute(); 

但這不是插入小時,分鐘,秒,毫秒DB?我如何從JDBC中插入這些信息?提前致謝。我覺得很難理解日期和時間的東西..這麼多的變化無處不在..

編輯

表結構爲:

enter image description here

編輯

方法cvtToGmt()來自How to convert a local date to GMT

回答

2

EDIT2

使用callableStatement.setTimestamp() - 這將當作一個時間戳。 javax.sql.Timestamp延伸java.util.Date所以你不需要轉換。

上一頁

也許cvtToGmt()功能切分。

您的表格中可能有錯誤的列類型,即不存儲Date

Date列類型:YYYY-MM-DDhttp://msdn.microsoft.com/en-ie/library/bb630352.aspx

Datetime列類型:YYYY-MM-DD hh.mm.ss.nnnhttp://msdn.microsoft.com/en-ie/library/ms187819.aspx

+0

感謝時間戳正在工作 – UDPLover

4

您需要使用java.sql.Timestampjava.sql.Date

java.util.Date僅僅是 「真正的」 日期欄,將刪除部分時間。如果您需要存儲日期,那麼您必須使用java.sql.Timestamp

From the Javadocs

要使用SQL DATE的定義符合,由java.sql.Date實例包裝的毫秒值必須通過設置時,分,秒和毫秒「規範化」在與實例相關聯的特定時區中爲零。

當然,你需要使用setTimestamp(),而不是setDate()爲好。

+0

感謝時間戳正在工作 – UDPLover