Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * ----- INSTRUÇÕES -----
- *
- *
- * 1) baixar a biblioteca de conexão do PGSQL com o JAVA:
- ----> https://jdbc.postgresql.org/download/postgresql-9.4-1201.jdbc4.jar
- 2) Botão Direito no Projeto ---> Propriedades ---> Java Build Path ---> Add External Jar ---> Selecionar Biblioteca Baixada
- *
- *
- *
- */
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.Statement;
- public class Principal {
- public static Connection connection = null;
- public static String host = "127.0.0.1:5432"; // Host e Porta padrões (5432 = Porta padrão do PGSQL)
- public static String database = "teste"; // Nome da Database
- public static String usuario = "postgres"; // Nome de Usuário padrão do PGSQL
- public static String senha = "felipe"; // Password do PGSQL;
- public static void main(String[] args) {
- try
- {
- Class.forName("org.postgresql.Driver");
- connection = DriverManager.getConnection(
- "jdbc:postgresql://"+host+"/"+database, usuario,
- senha);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- System.out.println("Conexão ao Host "+host+" - Database: "+"'"+database+"'"+" Falhou!");
- return;
- }
- System.out.println("Conexão Realizada com Sucesso à Database: "+"'"+database+"' !");
- /* Estou utilizando a Tabela chamada 'pessoas' para testar.
- *
- * id ---> INTEGER NOT NULL PRIMARY KEY
- * nome ---> VARCHAR(50) NOT NULL
- * idade ---> INTEGER NOT NULL
- * dinheiro ---> DECIMAL NOT NULL DEFAULT 0
- *
- */
- insert_update("INSERT INTO pessoas VALUES (2, 'Felipe', 18, 550.32); ");
- delete("DELETE FROM pessoas");
- }
- public static void insert_update(String query) // Metódo para INSERT e UPDATE
- {
- if(connection != null)
- {
- Statement st = null;
- try
- {
- st = connection.createStatement(); // Criando Statement a partir da Conexão do Banco
- st.executeUpdate(query);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- return;
- }
- System.out.println("Inserção / Atualização realizada com sucesso utilizando a query: ");
- System.out.println("-----> "+query);
- }
- }
- public static void delete(String query) // Método para DELETE
- {
- if(connection != null)
- {
- Statement st = null;
- try
- {
- st = connection.createStatement(); // Criando Statement a partir da Conexão do Banco
- st.executeQuery(query);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- return;
- }
- System.out.println("Deleção realizada com sucesso utilizando a query: ");
- System.out.println("-----> "+query);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement