Erro para conectar no banco de dados

11 respostas
Galego_Henrique

Galera estou tentando estudar este código que minha professora passou, mas está dando um erro, alguém poderia me dizer sobre? Já no meu note o erro é outro este aqui é no DEsktop.

import java.sql.*; public class Conecta { public static void main(String[] args) { System.out.println("Teste de Acesso e consulta ao Mysql"); try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); } catch(Exception E) { System.err.println("Unable to load driver."); E.printStackTrace(); } try { Connection Conn = DriverManager.getConnection("jdbc:mysql://localhost/moduloIII","root",""); Statement Stmt = Conn.createStatement(); ResultSet RS = Stmt.executeQuery("Select * from usuario"); while (RS.next()) { System.out.println(RS.getString(1)+" "+RS.getString(2)); } RS.close(); Stmt.close(); Conn.close(); } catch (SQLException E) { System.out.println("SQLException: " + E.getMessage()); System.out.println("SQLState: " + E.getSQLState()); System.out.println("VendorError: " + E.getErrorCode()); } } }

Erro:

SQLException: Communication failure during handshake. Is there a server running on localhost:3306?
SQLState: null
VendorError: 0

11 Respostas

Galego_Henrique

Erro no notebook:

SQLException: No suitable driver found for jdbc : mysql : localhost/moduloIII
SQLState: 08001
VendorError: 0

L

Provavelmente não foi adicionado o driver do MySql no teu projeto para realizar a conexão, para resolver clique com o botão direito no pacote bibliotecas no teu projeto e em adicionar selecionar o driver JDBC do MySql.

Galego_Henrique

Desculpe locomatt , mas teria como explicar mais detalhado isso? Eu sou meio novo nisso… Seria dentro da classe que está tal código?

romarcio

Para baixar o Driver JDBC do Mysql, acesse: http://dev.mysql.com/downloads/connector/j/

Galego_Henrique

romarcio:
Para baixar o Driver JDBC do Mysql, acesse: http://dev.mysql.com/downloads/connector/j/

Romarcio, eu baixei aqui e adicionei no JDK profile, não sei se realmente era isso a fazer, como eu disse sou iniciante, mas enfim…
O erro continua.

SQLException: No suitable driver found for jdbc:mysql:localhost/moduloIII
SQLState: 08001
VendorError: 0

Galego_Henrique

Galera, dei conta de resolver o problema, a solução era colocar o Driver dentro da pasta que continha a outra versão do Driver, diferente do que eu achava que seria apenas mudar o profile do JDK.

R

[quote]
Pessoal estou com dificuldades em resolver este codigo. O arquivo de conexao esta funcionando, porem nao consigo concluir a inclusao de dados, esta aprecendo o erro de java.lang.NullPointerException.

[quote]

Codigo de conexao:

package view;

import java.sql.*;

/**
 *
 * @author Ricardo
 */
public class ConexaoJDBC {
    /**
     *
     */
    public boolean conecta(){   
           
        boolean result = true;
           
            try{   
                 Class.forName("com.mysql.jdbc.Driver");
                 System.out.println("Driver carregado com sucesso");
                 
    
                 Connection conecta = DriverManager.getConnection("jdbc:mysql://192.168.1.103:3306/VideoAulaJDBC","Ricardo","ric1206");   
                 System.out.println ("Conexao com BD OK");  
                 
                 conecta.close();   
               
            }   catch (SQLException ex) {   
                    System.out.println("Problemas na conexao com o banco de dados."+ex);   
            }   catch (ClassNotFoundException ex) {   
                    System.out.println("Driver JDBC-ODBC nao encontrado: "+ ex); 
                    
        }   
        return result;
           
    }   
       
}

Codigo de inserção de dados:

package view;

import java.sql.*;


/**
 *
 * @author edge
 */
public class JCadClienteView extends javax.swing.JDialog {
    private Class<? extends ConexaoJDBC> Connection;
    private Object conecta;

    /** Creates new form JCadClienteView */
    public JCadClienteView(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(196, 196, 196));

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 24));
        jLabel1.setText("Cadastro de Clientes");
        jLabel1.setName("Cadastro de CLientes"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(100, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(93, 93, 93))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addContainerGap())
        );

        jPanel2.setBackground(new java.awt.Color(196, 196, 196));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 438, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 15, Short.MAX_VALUE)
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastro de Clientes"));
        jPanel3.setToolTipText("");

        jLabel4.setText("CPF");

        jLabel2.setText("Nome");

        jLabel3.setText("Endereço");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jButton1.setText("Limpar");

        jButton2.setText("Salvar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Fechar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(113, 113, 113)
                        .addComponent(jButton3)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(33, 33, 33))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)
                    .addComponent(jButton3))
                .addGap(33, 33, 33)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        try{
            ConexaoJDBC con = new ConexaoJDBC();
            con.conecta();
            Connection conn = null;
            
            //String para inserir no banco
            String query="INSERT INTO Cliente (Nome,Endereco,CPF) VALUES (?,?,?)";

            //Cria a conexão
            PreparedStatement stmt = conn.prepareStatement(query);

            //seta os valores
            stmt.setString(1, jTextField1.getText());
            stmt.setString(2, jTextField2.getText());
            stmt.setString(3, jTextField3.getText());
            
            //Atualiza o banco de dados
            stmt.executeUpdate();

            //fecha
            stmt.close();
           
            
            } catch (SQLException e) {   
            }  

           
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      System.exit(0);
    }                                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                JCadClienteView dialog = new JCadClienteView(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration                   

}
J

Sua Conexão esta estranha tenta usar essa

public class ConnectionFactoryh {

    private static Connection conn = null;
    //private static Configuracao conf = UtilSesmtAtividade.conf;

    private static Connection conectar() {
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(ConnectionFactoryh.class.getName()).log(Level.SEVERE, null, ex);
            }
             String url = "jdbc:mysql://127.0.0.1:3306/banco";
              return DriverManager.getConnection(url, usuario, senha);
       } catch (CommunicationsException e){
            JOptionPane.showMessageDialog(null, "Erro na comunicação "+e.getMessage(),"ERRO", JOptionPane.ERROR_MESSAGE);
            return null;
        } catch (SQLException e){
            JOptionPane.showMessageDialog(null, "Erro no SQL "+e.getMessage(),"ERRO", JOptionPane.ERROR_MESSAGE);
            throw new RuntimeException(e);
        }
       
    }

    public static Connection getConection() {
        try {
            if (conn == null || conn.isClosed()) {
                conn = conectar();
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro no sql: "+ex.getMessage(),"ERRO", JOptionPane.ERROR_MESSAGE);
            throw new RuntimeException(ex);
        }
        return conn;
    }


    public static void closeConnection(Connection conn, PreparedStatement ps) {
        try {
            ps.close();
            conn.close();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void closeConnection(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            ps.close();
            conn.close();
            rs.close();
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }
}

e tenta chamar assim

public boolean incluir(CadMat cad) {

        boolean bok = false;

        Connection conn = null;
        PreparedStatement ps = null;

        conn = ConnectionFactoryh.getConection();
        if (conn == null) {
            return bok;
        }

        sql = "INSERT INTO cadmat (cod_cadmat, des_cadmat, qtd_cadmat, codmat_cadmat, cod_cadosm)";
        sql += "VALUES(? ,? , ?, ?, ?);";
        try {
            ps = conn.prepareStatement(sql);
            ps.setLong(1, cad.getCod_cadmat());
            ps.setString(2, cad.getDes_cadmat());
            ps.setInt(3, cad.getQtd_cadmat());
            ps.setLong(4, cad.getCodmat_cadmat());
            ps.setLong(5, cad.getCod_cadosm());
            ps.executeUpdate();
            bok = true;
        } catch (Exception e){
            JOptionPane.showMessageDialog(null, "Erro na comunicação "+e,"ERRO", JOptionPane.ERROR_MESSAGE);
        } finally {
            ConnectionFactoryh.closeConnection(conn, ps);
        }

        return bok;
    }
R
J

so para vc fazer um teste para ver se ocorreu tudo certo mesmo
se vc quiser pode tirar a variável bOk e colocar

em true

System.out.print("ok");

ou

em false

System.out.print("erro");
J
public class ConexaoJDBC {  
    /** 
     * 
     */  
    public boolean conecta(){     
             
        boolean result = true;  
             
            try{     
                 Class.forName("com.mysql.jdbc.Driver");  
                 System.out.println("Driver carregado com sucesso");  
                   
      
                 Connection conecta = DriverManager.getConnection("jdbc:mysql://192.168.1.103:3306/VideoAulaJDBC","Ricardo","ric1206");     
                 System.out.println ("Conexao com BD OK");    
                   
                 conecta.close();     
                 
            }   catch (SQLException ex) {     
                    System.out.println("Problemas na conexao com o banco de dados."+ex);     
            }   catch (ClassNotFoundException ex) {     
                    System.out.println("Driver JDBC-ODBC nao encontrado: "+ ex);   
                      
        }     
        return result;  
             
    }     
         
}

o que estava esranho nesse codigo seu é que vc so estava testando a conexão

e voltando o um boolean true ou false

na verdade so faltava vc retornar a conexao

Criado 5 de maio de 2012
Ultima resposta 22 de jan. de 2013
Respostas 11
Participantes 5