Ir ao conteúdo
  • Cadastre-se

Java Erro ao conectar no banco de dados postgresql


Ir à solução Resolvido por herbertbahia,

Posts recomendados

Fiz a conexão no banco de dados usando o netbeans mas não está encontrando o DRIVE, aparentemente está tudo correto, mas retorna sempre o erro: No suitable driver found for jdbc:postgresql:localhost:5432/ProjetoFolha

public class ConexaoBD {
    
    public Statement stn; //pesquisa no banco de dados
    public ResultSet rs; // armazena o resultado da pesquisa
    private String driver = "org.postgresql.Driver"; //identifica o nosso serviço BD
    private String caminho = "jdbc:postgresql://localhost:5432/ProjetoFolha"; //Qual o caminho do BD
    private String usuario = "postgres";
    private String senha = "xxxxxxx";
    public Connection con; 
    
    public void conexao(){
        
        try {
            System.setProperty("jdbc.Drivers", driver);
            con=DriverManager.getConnection(caminho, usuario, senha);
            JOptionPane.showMessageDialog(null, "Conexão efetuada com sucesso");
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro na conexão efetuada!\n"+ex.getMessage());
        }
    }

 

Link para o comentário
Compartilhar em outros sites

3 horas atrás, bngomes disse:

Teste trocando jdbc.Drivers para jdbc.driverClassName e veja se conecta... nas minhas configurações é com essa propriedade.. 

Eu coloquei bem como você digitou e continua aparecendo a  mesma mensagem...eu devo colocar um nome de classe no lugar de ClassName no jdbc.driver...? Será que eu não tenho um problema de biblioteca?

Postgresql.png

Link para o comentário
Compartilhar em outros sites

3 horas atrás, nigolino disse:

o que devo configurar no pom?

depende a finalidade do seu sistema por exmeplo se for jdbc aqui esta um exemplo

 

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>herbert.company</groupId>
	<artifactId>jdbc-Jdev</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<name>jdbc-Jdev</name>
	<!-- FIXME change it to the project's website -->
	<url>http://www.example.com</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
	</properties>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/junit/junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.13</version>
			<scope>test</scope>
		</dependency>


		<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<version>42.2.16</version>
		</dependency>

	</dependencies>

	<build>
		<pluginManagement><!-- lock down plugins versions to avoid using Maven 
				defaults (may be moved to parent pom) -->
			<plugins>
				<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
				<plugin>
					<artifactId>maven-clean-plugin</artifactId>
					<version>3.1.0</version>
				</plugin>
				<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
				<plugin>
					<artifactId>maven-resources-plugin</artifactId>
					<version>3.0.2</version>
				</plugin>
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.8.0</version>
				</plugin>
				<plugin>
					<artifactId>maven-surefire-plugin</artifactId>
					<version>2.22.1</version>
				</plugin>
				<plugin>
					<artifactId>maven-jar-plugin</artifactId>
					<version>3.0.2</version>
				</plugin>
				<plugin>
					<artifactId>maven-install-plugin</artifactId>
					<version>2.5.2</version>
				</plugin>
				<plugin>
					<artifactId>maven-deploy-plugin</artifactId>
					<version>2.8.2</version>
				</plugin>
				<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
				<plugin>
					<artifactId>maven-site-plugin</artifactId>
					<version>3.7.1</version>
				</plugin>
				<plugin>
					<artifactId>maven-project-info-reports-plugin</artifactId>
					<version>3.0.0</version>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>
package conexaojdbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class SingleConection {
	private static String url= "jdbc:postgresql://localhost:5432/nomebanco";
	private static String user = "postgres";
	private static String password= "admin";
	private static Connection connection = null;
	
	static {
		conectar();
	}
	
	public SingleConection() {
		conectar();
	}
	
	private static void conectar() {
		try {
			if(connection==null) {
				Class.forName("org.postgresql.Driver");
				connection = DriverManager.getConnection(url, user, password);
				connection.setAutoCommit(false);
				System.out.println("Conectou com Sucesso");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		return connection;
	}
	

}

 

Link para o comentário
Compartilhar em outros sites

48 minutos atrás, herbertbahia disse:

depende a finalidade do seu sistema por exmeplo se for jdbc aqui esta um exemplo

 


<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>herbert.company</groupId>
	<artifactId>jdbc-Jdev</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<name>jdbc-Jdev</name>
	<!-- FIXME change it to the project's website -->
	<url>http://www.example.com</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.7</maven.compiler.source>
		<maven.compiler.target>1.7</maven.compiler.target>
	</properties>

	<dependencies>
		<!-- https://mvnrepository.com/artifact/junit/junit -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.13</version>
			<scope>test</scope>
		</dependency>


		<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
		<dependency>
			<groupId>org.postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<version>42.2.16</version>
		</dependency>

	</dependencies>

	<build>
		<pluginManagement><!-- lock down plugins versions to avoid using Maven 
				defaults (may be moved to parent pom) -->
			<plugins>
				<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
				<plugin>
					<artifactId>maven-clean-plugin</artifactId>
					<version>3.1.0</version>
				</plugin>
				<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
				<plugin>
					<artifactId>maven-resources-plugin</artifactId>
					<version>3.0.2</version>
				</plugin>
				<plugin>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>3.8.0</version>
				</plugin>
				<plugin>
					<artifactId>maven-surefire-plugin</artifactId>
					<version>2.22.1</version>
				</plugin>
				<plugin>
					<artifactId>maven-jar-plugin</artifactId>
					<version>3.0.2</version>
				</plugin>
				<plugin>
					<artifactId>maven-install-plugin</artifactId>
					<version>2.5.2</version>
				</plugin>
				<plugin>
					<artifactId>maven-deploy-plugin</artifactId>
					<version>2.8.2</version>
				</plugin>
				<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
				<plugin>
					<artifactId>maven-site-plugin</artifactId>
					<version>3.7.1</version>
				</plugin>
				<plugin>
					<artifactId>maven-project-info-reports-plugin</artifactId>
					<version>3.0.0</version>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

package conexaojdbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class SingleConection {
	private static String url= "jdbc:postgresql://localhost:5432/nomebanco";
	private static String user = "postgres";
	private static String password= "admin";
	private static Connection connection = null;
	
	static {
		conectar();
	}
	
	public SingleConection() {
		conectar();
	}
	
	private static void conectar() {
		try {
			if(connection==null) {
				Class.forName("org.postgresql.Driver");
				connection = DriverManager.getConnection(url, user, password);
				connection.setAutoCommit(false);
				System.out.println("Conectou com Sucesso");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
		return connection;
	}
	

}

 

Estou tentando configurar o "pom", mas não estou conseguindo porque não estou usando o jdbc. Vou postar meus códigos para que possam ver...

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>ProjetoClinica</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <name>ProjetoClinica</name>
    <repositories>
        <repository>
            <id>unknown-jars-temp-repo</id>
            <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
            <url>file:${project.basedir}/lib</url>
        </repository>
        
        <repository>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>VERSION</version>
        </repository>
        
    </repositories>
           
 </project>
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controle;

import java.sql.*;
import java.sql.DriverManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author SCHRENK
 */
public class ConexaoBD {
    
    public Statement stm; //pesquisa no banco de dados
    public ResultSet rs; // armazena o resultado da pesquisa
    private String driver = "org.postgresql.Driver"; //identifica o nosso serviço BD
    private String caminho = "jdbc:postgresql://localhost:5433/Postgres"; //Qual o caminho do BD
    private String usuario = "postgres";
    private String senha = "1234567";
    public Connection con; 
    
    public void conexao(){
        
        try {
            System.setProperty("jdbc.DriverClassName", driver);//setar a propriedade do driver de conexão
            con=DriverManager.getConnection(caminho, usuario, senha);
            JOptionPane.showMessageDialog(null, "Conexão efetuada com sucesso");
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro na conexão efetuada!\n"+ex.getMessage());
        }
    }
    
    public void desconecta(){
        try {
            con.close();
            JOptionPane.showMessageDialog(null, "Desconectado com sucesso");
        } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Erro ao desconectar efetuada com sucesso"+ex.getMessage());
        }
    }
}
The project com.mycompany:ProjetoClinica:1.0-SNAPSHOT (C:\ProjetoClinica\pom.xml) has 4 errors
    Malformed POM C:\ProjetoClinica\pom.xml: Unrecognised tag: 'groupId' (position: START_TAG seen ...<repository>\n            <groupId>... @22:22)  @ C:\ProjetoClinica\pom.xml, line 22, column 22 -> [Help 2]
    'repositories.repository.id' is missing. @ line 21, column 21
    'repositories.repository.[null].url' is missing. @ line 21, column 21
    Invalid artifact repository: Repository identifier missing -> [Help 3]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

 

Link para o comentário
Compartilhar em outros sites

35 minutos atrás, nigolino disse:

não estou usando o jdbc.

ué 

 

35 minutos atrás, nigolino disse:

System.setProperty("jdbc.DriverClassName", driver);//setar a propriedade do driver de conexão

 

35 minutos atrás, nigolino disse:

private String caminho = "jdbc:postgresql://localhost:5433/Postgres"; //Qual o caminho do BD

 

Link para o comentário
Compartilhar em outros sites

  • Solução
3 minutos atrás, nigolino disse:

desculpa aí, eu quis dizer que estava usando jdbc...e não springboot..

entendir, apesar de um ser desktop e outro web a classe de conexao e quase a mesma coisa só muda o jars mesmo, nao tem porque nao funcionar é só da uma conferida na senha do bdd boa sorte nos estudos

Link para o comentário
Compartilhar em outros sites

  • 2 semanas depois...

Pessoal, estou com mais uma dúvida com relação a conversão do ComboBoxBanco o netbeans retorna a mensagem "Objeto não pode ser convertido para String", tentei fazer o casting, mas está dando erro na execução, somente com a conta banco...o combo foi criado no banco de dados e no programa como int...

	private void jButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // Ação Salvar:
        mod.setNumFunc(Integer.parseInt(jTextFieldNumFunc.getText()));
        mod.setNumVinc(Integer.parseInt(jTextFieldNumVinc.getText()));
        mod.setNumPen(Integer.parseInt(jTextFieldNumPen.getText()));
        mod.setNome(jTextFieldNome.getText());
        mod.setSalarioBase(Double.parseDouble(jTextFieldSalarioBase.getText()));
        mod.setEmail(jTextFieldEmail.getText());
        mod.setDataNascim(jTextFieldDataNascim.getText());
        //mod.setBanco((Integer)jComboBoxBanco.getSelectedItem());
        mod.setBanco(Integer.parseInt(jComboBoxBanco.getSelectedItem()));
        //mod.setBanco((int) jComboBoxBanco.getSelectedItem());
        mod.setAgencia(Integer.parseInt(jTextFieldAgencia.getText()));
        mod.setConta(Integer.parseInt(jTextFieldConta.getText()));
        control.Salvar(mod);
    }                                   

 

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...