[英]How to pass string with ' ' (timestamp) in prepared statement?
我正在嘗試執行以下查詢
INSERT INTO hotspot(timestamp) VALUES
(timestamp with time zone '2012-10-25 14:00:00 +05:00' at time zone 'EET');
我想將時間戳作為變量傳遞。
我的時間戳列是帶時區的時間戳類型。
你知道如何做到這一點嗎?
當我做...(Java,Postgresql)
String stm= "INSERT INTO hotspot(timestamp) VALUES(timestamp with time zone ? at time zone 'EET')";
pst = con.prepareStatement(stm);
pst.setString(1, "2012-08-24 14:00:00 +05:00");
pst.executeUpdate();
我在“$ 1”或附近收到語法錯誤
無論如何我能克服這個錯誤嗎? 先感謝您!!
更新:我嘗試通過以下方式使用setTimestamp ...
Calendar c=Calendar.getInstance(TimeZone.getTimeZone("GMT+05:00"));
String stm= "INSERT INTO hotspot(timestamp) VALUES(?)";
pst = con.prepareStatement(stm);
pst.setTimestamp(1,Timestamp.valueOf("2012-01-05 14:00:00"), c );
pst.executeUpdate();
我想數據庫中的正確值應該是(關於我的本地時區是EET(+02))
2012-01-05 11:00:00 +02
但使用pgadmin我檢查值,我得到
2012-01-05 14:00:00 +02
有什么建議么?
Federico Cristina非常正確, setTimestamp
是執行此操作的正確方法。
語法錯誤的原因是您在傳遞參數時無法使用前導類型說明符指定類型。 INTEGER '4'
樣式僅對文字有效,而不對參數有效。
您的代碼將被PREPARE
天,然后EXECUTE
在協議層d。 這里,如果我發生了什么PREPARE
它:
regress=> PREPARE blah(timestamptz) AS INSERT INTO hotspot(timestamp) VALUES(timestamp with time zone $1 at time zone 'EET');
ERROR: syntax error at or near "$1"
LINE 1: ...otspot(timestamp) VALUES(timestamp with time zone $1 at time...
由於在查詢參數中指定了數據類型,因此可以省略它,而是編寫:
String stm= "INSERT INTO hotspot(\"timestamp\") VALUES(? at time zone 'EET')";
請注意,我也引用了雙重"timestamp"
,因為它是一個保留字。 它在某些情況下不會引用但在其他情況下不會引用。 選擇數據類型名稱或保留字作為列名通常是一個壞主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.