elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  Problema con la conexión a la BD
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema con la conexión a la BD  (Leído 1,260 veces)
BJM

Desconectado Desconectado

Mensajes: 41


Ver Perfil
Problema con la conexión a la BD
« en: 11 Octubre 2016, 00:32 am »

Esta es la clase que contiene el codigo para la conexion con la base de datos

Código
  1. package drone;
  2. import java.sql.*;
  3. import javax.swing.*;
  4.  
  5. public class Conexion {
  6.    public String db = "prototipo";
  7.    public String user= "root";
  8.    public String pass="";
  9.    public String url= "jdbc:mysql://localhost/"+db;
  10.    public Conexion()
  11.    {
  12.            }
  13.   public Connection conectar()
  14.   {
  15.       java.sql.Connection link=null;
  16.       Statement st=null;
  17.       try{
  18.                 Class.forName("com.mysql.jdbc.Driver");
  19.                 link=DriverManager.getConnection(this.url, this.user, this.pass);
  20.                 if(link!=null){
  21.                     JOptionPane.showMessageDialog(null, "conexion establecida");
  22.                 }
  23.                 /*if(link!=null){
  24.                      st=link.createStatement();
  25.                  }*/
  26.   }
  27.       catch(Exception e)
  28.       {
  29.           JOptionPane.showMessageDialog(null, "fallo conexion");
  30.           JOptionPane.showMessageDialog(null, e);
  31.       }
  32.       return link;
  33.   }
  34.    }
  35.  
  36.  

Esta es la clase Login que contiene el llamado al metodo conectar() de la clase Conexion, aqui tambien se genera el evento de boton

Código
  1. package drone;
  2.  
  3. import java.awt.BorderLayout;
  4. import java.awt.Toolkit;
  5. import java.sql.*;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8. import javax.swing.JOptionPane;
  9. import java.lang.*;
  10.  
  11.  
  12. public class Login extends javax.swing.JFrame {
  13.  
  14.  
  15.    public Login() {
  16.        initComponents();
  17.        this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
  18.        PnlFondo fondo = new PnlFondo();
  19.        this.setLayout(new BorderLayout());
  20.        this.add(fondo,BorderLayout.CENTER);
  21.  
  22.    }
  23.  
  24.    /**
  25.      * This method is called from within the constructor to initialize the form.
  26.      * WARNING: Do NOT modify this code. The content of this method is always
  27.      * regenerated by the Form Editor.
  28.      */
  29.    @SuppressWarnings("unchecked")
  30.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  31.    private void initComponents() {
  32.  
  33.        jButton1 = new javax.swing.JButton();
  34.        jLabel1 = new javax.swing.JLabel();
  35.        jLabel2 = new javax.swing.JLabel();
  36.        usuario = new javax.swing.JTextField();
  37.        jLabel3 = new javax.swing.JLabel();
  38.        contraseña = new javax.swing.JPasswordField();
  39.        jButton2 = new javax.swing.JButton();
  40.  
  41.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  42.  
  43.        jButton1.setText("Registrarse");
  44.  
  45.        jLabel1.setText("Iniciar Sesion");
  46.  
  47.        jLabel2.setText("Usuario");
  48.  
  49.        jLabel3.setText("Contraseña");
  50.  
  51.        jButton2.setText("Aceptar");
  52.        jButton2.addActionListener(new java.awt.event.ActionListener() {
  53.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  54.                jButton2ActionPerformed(evt);
  55.            }
  56.        });
  57.  
  58.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  59.        getContentPane().setLayout(layout);
  60.        layout.setHorizontalGroup(
  61.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  62.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  63.                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  64.                .addComponent(jButton1)
  65.                .addGap(46, 46, 46))
  66.            .addGroup(layout.createSequentialGroup()
  67.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  68.                    .addGroup(layout.createSequentialGroup()
  69.                        .addGap(89, 89, 89)
  70.                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  71.                            .addComponent(jLabel3)
  72.                            .addComponent(jLabel2))
  73.                        .addGap(75, 75, 75)
  74.                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  75.                            .addComponent(usuario, javax.swing.GroupLayout.DEFAULT_SIZE, 64, Short.MAX_VALUE)
  76.                            .addComponent(contraseña)))
  77.                    .addGroup(layout.createSequentialGroup()
  78.                        .addGap(163, 163, 163)
  79.                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  80.                            .addComponent(jButton2)
  81.                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))))
  82.                .addContainerGap(116, Short.MAX_VALUE))
  83.        );
  84.        layout.setVerticalGroup(
  85.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  86.            .addGroup(layout.createSequentialGroup()
  87.                .addGap(20, 20, 20)
  88.                .addComponent(jButton1)
  89.                .addGap(33, 33, 33)
  90.                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
  91.                .addGap(18, 18, 18)
  92.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  93.                    .addGroup(layout.createSequentialGroup()
  94.                        .addComponent(jLabel2)
  95.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, 27, Short.MAX_VALUE)
  96.                        .addComponent(jLabel3)
  97.                        .addGap(159, 159, 159))
  98.                    .addGroup(layout.createSequentialGroup()
  99.                        .addComponent(usuario, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
  100.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  101.                        .addComponent(contraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  102.                        .addGap(29, 29, 29)
  103.                        .addComponent(jButton2)
  104.                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
  105.        );
  106.  
  107.        pack();
  108.    }// </editor-fold>                        
  109.  
  110.    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  111.  
  112.        String user=usuario.getText();
  113.        String pass=contraseña.getText();
  114.        if ((user.length()==0)||(pass.length()==0)){
  115.           JOptionPane.showMessageDialog(rootPane, "Campo usuario o contraseña vacio");
  116.             }else{
  117.            Conexion mysql= new Conexion();
  118.       Connection conn= mysql.conectar();
  119.       if(conn!=null){
  120.           JOptionPane.showMessageDialog(rootPane, "Conexion con base de datos");
  121.       }
  122.              try {
  123.                  Statement sentencia= conn.createStatement();
  124.                ResultSet rs;
  125.                rs = sentencia.executeQuery("SELECT * FROM usuarios WHERE Usuario="+user+" && Contraseña="+pass+"");
  126.                int encontrado=rs.getRow();
  127.                if(encontrado==1){
  128.                    Menu inicio=new Menu();
  129.                    inicio.setVisible(true);
  130.                }
  131.                else{
  132.                    JOptionPane.showMessageDialog(rootPane, "Los datos son incorrectos");
  133.                }
  134.            } catch (SQLException ex) {
  135.                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
  136.            }
  137.        }
  138.        //if (user.equals()&&pass.equals());
  139.    }                                        
  140.  
  141.    /**
  142.      * @param args the command line arguments
  143.      */
  144.    public static void main(String args[]) {
  145.        /* Set the Nimbus look and feel */
  146.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  147.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  148.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  149.          */
  150.        try {
  151.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  152.                if ("Nimbus".equals(info.getName())) {
  153.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  154.                    break;
  155.                }
  156.            }
  157.        } catch (ClassNotFoundException ex) {
  158.            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  159.        } catch (InstantiationException ex) {
  160.            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  161.        } catch (IllegalAccessException ex) {
  162.            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  163.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  164.            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  165.        }
  166.        //</editor-fold>
  167.  
  168.        /* Create and display the form */
  169.        java.awt.EventQueue.invokeLater(new Runnable() {
  170.            public void run() {
  171.                new Login().setVisible(true);
  172.            }
  173.        });
  174.  
  175.    }
  176.  
  177.    // Variables declaration - do not modify                    
  178.    private javax.swing.JPasswordField contraseña;
  179.    private javax.swing.JButton jButton1;
  180.    private javax.swing.JButton jButton2;
  181.    private javax.swing.JLabel jLabel1;
  182.    private javax.swing.JLabel jLabel2;
  183.    private javax.swing.JLabel jLabel3;
  184.    private javax.swing.JTextField usuario;
  185.    // End of variables declaration                  
  186. }
  187.  
  188.  

Gracias por adelantado quien me pueda ayudar


En línea

BJM

Desconectado Desconectado

Mensajes: 41


Ver Perfil
Re: Problema con la conexión a la BD
« Respuesta #1 en: 11 Octubre 2016, 01:04 am »

Debo agregar que e IDE que utilizo es netbeans el cual me indica Dereferencing possible null pointer en la linea Statement sentencia= conn.createStatement(); de la clase Login


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Problema BlueZScanner y problema de conexión
Hacking Mobile
Kasswed 3 6,288 Último mensaje 6 Mayo 2006, 22:04 pm
por Gospel
[SOLUCIONADO] Problema conexión Chat Java(funciona en LAN,no en conexión Remota) « 1 2 »
Java
-Localhost- 10 15,903 Último mensaje 24 Julio 2010, 20:15 pm
por Debci
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines