Insert and read data postgresql - Java JDBC

Java examples for JDBC:Postgresql

Description

Insert and read data postgresql

Demo Code


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.dataforum.oracle.Oracle;

public class Postgres {

  public static void main(String[] args) {
    try {/*w w  w  .  j a  v a  2  s. c  om*/
      Postgres postgres = new Postgres();
      String sql = "create table users(id int primary key not null,name text,email text)";
      postgres.execute(sql);
      
      String sql1 = "insert into users values(1,'Jack','asdf@live.com')";
      postgres.execute(sql1);
      String sql = "select * from users";
      ResultSet rs = postgres.select(sql);
      while (rs.next()) {
        System.out.println("ID:"+rs.getString(1)+"\n"+" "+rs.getString(2)+"\n"+" "+rs.getString(3));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private Connection conn = null;
  private String url = "jdbc:postgresql://localhost:5432/userName";
  private String driver = "org.postgresql.Driver";
  private String user = "Jack";
  private String password = "Jack";

  public Connection create() {
    try {
      Class.forName(driver);
      conn = DriverManager.getConnection(url, user, password);
    } catch (Exception ex) {
      System.out.println(ex);
    }
    return conn;
  }

  public ResultSet select(String sql) {
    Connection conn = create();
    ResultSet rs = null;
    try {
      Statement st = conn.createStatement();
      rs = st.executeQuery(sql);
    } catch (Exception e) {
      System.out.println(e);
    } finally {
      // conn.close();
    }
    return rs;
  }

  public void execute(String sql) {
    Connection conn = create();
    ResultSet rs = null;
    try {
      Statement st = conn.createStatement();
      st.executeUpdate(sql);
    } catch (Exception e) {
      System.out.println(e);
    }

  }
}

Related Tutorials