Koneksi dan query ke PostgreSQL – Java

Kalo yang sudah biasa pake MySQL trus nyobain (entah belajar ato kepaksa karna client minta pake postgresql) biasanya rada repot karna query seperti SELECT NAMA FROM BIODATA ga bisa, harus pake petik 2 di setiap field atau nama tabel, seperti SELECT “NAMA” FROM “BIODATA”, ga tau apa ada konfigurasi lain yang bisa lebih fleksibel.( sory pengetahuanku blom nyampe he he)

contoh code pake java.

package DB;

import java.sql.CallableStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Properties;


public class PostgreSQLJDBC {
    private static java.sql.Connection conn;
    public static void main(String args[]) {
      
       try {
           String url = "jdbc:postgresql://localhost:5432/PBB";
           Properties props = new Properties();
           props.setProperty("user","postgres");
           props.setProperty("password","j@mbukl03tuk");
           //props.setProperty("ssl","true");
           conn = DriverManager.getConnection(url, "postgres","bandung11");
       
           java.sql.Statement st =  conn.createStatement();
           String NOP="137107000100700100";       
           int prop=Integer.parseInt(NOP.substring(0,2));
           int dati2=Integer.parseInt(NOP.substring(2,4));      
           int kec=Integer.parseInt(NOP.substring(4,7));
           int kel=Integer.parseInt(NOP.substring(7,10));
           int blok=Integer.parseInt(NOP.substring(10,13));
           int nourut=Integer.parseInt(NOP.substring(13,17));
           int op=Integer.parseInt(NOP.substring(17,18));

      
            CallableStatement proc = conn.prepareCall("SELECT * FROM SPPT WHERE "
                    + "cast(\"PROPINSI\" as int)=? "
                    + "AND cast(\"DATI2\" as int)  = ? "
                    + "AND cast(\"KECAMATAN\" as int) = ?   "
                    + "AND cast(\"KELURAHAN\" as int) = ? "
                    + "AND cast(\"BLOK\" as int) =? "
                    + "AND cast(\"URUT\" as int) =? "
                    + "AND cast(\"JNSOP\" as int)=?");
            proc.setInt(1, prop);           
            proc.setInt(2, dati2);
            proc.setInt(3, kec);
            proc.setInt(4, kel);
            proc.setInt(5, blok);
            proc.setInt(6, nourut);
            proc.setInt(7, op); 
        
            System.out.println(proc.toString());
            final ResultSet rs= proc.executeQuery();
        
           while (rs.next())
           {
              System.out.print("Column 1 returned ");
              System.out.println(rs.getString("NM_WP_SPPT"));
              System.out.println(rs.getString("THN_PAJAK_SPPT"));
           } rs.close();
           st.close();
       
        } catch (Exception e) {
             e.printStackTrace();
             System.err.println(e.getClass().getName()+": "+e.getMessage());
             System.exit(0);
        }
   }
}

Happy coding…cmiieeww

Advertisements