Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.sql.Timestamp;
- import java.util.Date;
- import java.util.Properties;
- public class Main2 {
- public static void main(String[] args) {
- String USER="";
- String PASS="";
- Connection conn = null;
- Statement stmt=null;
- PreparedStatement pstmt=null;
- ResultSet rs=null;
- try {
- Class.forName("org.postgresql.Driver");
- String url = "jdbc:postgresql://localhost/db_test01";
- Properties props = new Properties();
- props.setProperty("user",USER);
- props.setProperty("password",PASS);
- conn = DriverManager.getConnection(url, props);
- System.out.println("接続に成功しました。");
- //pstmt=conn.prepareStatement("INSERT INTO public.\"PRODUCT\"(\"PRODUCT_CODE\",\"PRODUCT_NAME\",\"PRICE\",\"UPDATE_DATE\") VALUES(?,?,?,?)");
- pstmt=conn.prepareStatement("insert into public.product(product_code,product_name,price,update_date) values(?,?,?,?)");
- pstmt.setString(1, "BIKE002");
- pstmt.setString(2, "cannondale slate");
- pstmt.setInt(3, 200000);
- pstmt.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
- int count=pstmt.executeUpdate();
- System.out.println(count+"件のinsertに成功しました。");
- pstmt.close();
- stmt=conn.createStatement();
- String sql="select * from product";
- rs=stmt.executeQuery(sql);
- while(rs.next()){
- String productCode=rs.getString("product_code");
- String productName=rs.getString("product_name");
- int price=rs.getInt("price");
- Date updateDate=rs.getTimestamp("update_date");
- System.out.println(rs.getRow()+"行目のデータ");
- System.out.println(productCode);
- System.out.println(productName);
- System.out.println(price);
- System.out.println(updateDate);
- }
- rs.close();
- stmt.close();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- System.out.println(e.getErrorCode());
- System.out.println(e.getSQLState());
- System.out.println(e.getMessage());
- } finally {
- try{
- if(stmt!=null){
- stmt.close();
- }
- }catch (SQLException e) {
- e.printStackTrace();
- }
- try{
- if(pstmt!=null){
- pstmt.close();
- }
- }catch (SQLException e) {
- e.printStackTrace();
- }
- try {
- if (conn != null) {
- conn.close();
- System.out.println("切断しました。");
- }
- } catch (SQLException e) {
- System.out.println(e.getErrorCode());
- System.out.println(e.getSQLState());
- System.out.println(e.getMessage());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement