[pgsql-jp: 26156] Re: 日付データのDB 登録について

Kishimoto Yu kishimoto @ bisonsoft.co.jp
2002年 5月 28日 (火) 16:00:04 JST


山田@京都さんこんにちは、Kishimoto と申します。

On Tue, 28 May 2002 12:31:35 +0900
"Hiroyuki Yamada" <hiroyuki @ rh.is.hitachizosen.co.jp> 様 wrote:

>  下記プログラムは、現在時刻をテーブル登録するものなのですが、 d_date,
> d_time, d_timestampの各フィールドに String型データからDBへ値を登録したいので
> すが、どのようにしたら良いのかご教授ねがいませんでしょうか?
> 
> (例)
>  String date_field = "2002-11-05";
>  String time_field = "10:09:35";
>  String timestamp_field = "1980-09-21 15:42:13.123";
> のデータをttt_tableテーブルへ登録したい。

PostgreSQL + Java のコーディングは初めてなので
間違いがあったらご指摘ください。

当方の環境(PostgreSQL 7.1.3, JDBC 1.3.1)では
以下のコードで動作しましたが、お望みのものとは
違うでしょうか?

[Hizuke.java]
import java.lang.*;
import java.sql.*;

public class Hizuke {
        public static void main(String[] args) {

                Connection conn = null;
                String url = "jdbc:postgresql:testdb";
                String user = "postgres";
                String password = "";

                String date_field = "2002-11-05";
                String time_field = "10:09:35";
                String timestamp_field = "1980-09-21 15:42:13";

                try{
                        Class.forName("org.postgresql.Driver");
                        conn = DriverManager.getConnection(url, user, password);

                        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO ttt_table values (?,?,?)");
                        pstmt.clearParameters();
                        pstmt.setString(1, date_field);
                        pstmt.setString(2, time_field);
                        pstmt.setString(3, timestamp_field);

                        pstmt.executeUpdate();
                        conn.commit();

                        pstmt.close();
                        conn.close();

                } catch(SQLException e){
                        e.printStackTrace();
                } catch(Exception e){
                        e.printStackTrace();
                }
        }
}

[実行結果]

testdb=# \d ttt_table
                 Table "ttt_table"
  Attribute  |           Type           | Modifier
-------------+--------------------------+----------
 d_date      | date                     |
 d_time      | time                     |
 d_timestamp | timestamp with time zone |

testdb=# select * from ttt_table;
   d_date   |  d_time  |      d_timestamp
------------+----------+------------------------
 2002-11-05 | 10:09:35 | 1980-09-21 15:42:13+09
(1 row)


あと、済みません。

>  String timestamp_field = "1980-09-21 15:42:13.123";
                                                ^^^^
".123" の書き方はわかりませんでした。

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 Kishimoto Yu <kishimoto @ bisonsoft.co.jp>




pgsql-jp メーリングリストの案内