Method Save to Java with classes

3

I'm doing a java project with forms which I have to save and delete for this I think a class that is the class connection a different class for each of the forms in which the different methods of saving modify and eliminate and the forms.

but the save function does not work for me and I do not know why

Save Class

package clasesAdministrador;

import Conexion.conexion1;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.table.DefaultTableModel;
import formAdministrador.usuarios1ad;
import javax.swing.JOptionPane;

public class usuario1ad {
Conexion.conexion1 conn=new Conexion.conexion1();
public PreparedStatement sql;
public ResultSet datos, rs;
DefaultTableModel tabla = new DefaultTableModel();
Statement sent;

     public void Guardar(int num_usu, String nom_usu, String con1,String tipus)
{
    try
    {
    conn.Conectar();
    sql=conn.con.prepareStatement("insert into usuario (id_usu,nom_usu,con_usu,tip_usu) values ("+num_usu+",'"+nom_usu+"','"+con1+"','"+tipus+"')");
    sql.execute();
    conn.cerrar();
    }
    catch(SQLException ex)
    {
      System.out.println("ERROR AL GUARDAR...");
    }
} // FIN METODO GUARDAR  
} // FIN DE TODO

Conexion Class

package Conexion;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class conexion1{
public PreparedStatement sql; 
public ResultSet datos;   
public Connection con=null;  

  public void Conectar(){
       String db="jdbc:mysql://localhost:3306/sena";
       String usuario="root";
       String password="salomeaa";
       try
       {
           String controlador="com.mysql.jdbc.Driver";
           System.out.println("CONEXION CON BASE DE DATOS...." +db);
           Class.forName(controlador);
           con=DriverManager.getConnection(db,usuario,password);
           System.out.println("CONEXION EXITOSA");
       }
       catch(Exception ex)
       {
        System.out.println("Error "+ex.getMessage());
       } 
}
public void cerrar(){

if(con==null)
{
try
{ con.close();}
catch(Exception ex)
 { }
}

}

}

Java Form

public class usuarios1ad extends javax.swing.JFrame {
usuario1ad gg = new usuario1ad();

// too much code to put everything (buttons and others)

public void GuardarUsuario(){
this.tipUsu();
gg.Guardar(Integer.parseInt(num_usu.getText()),nom_usu.getText(),con1.getText(),tipus);
//  JOptionPane.showMessageDialog(null, "DATOS ALMACENADOS CORRECTAMENTE", "GUARDAR", JOptionPane.INFORMATION_MESSAGE);
}

num_usu: user id

nom_usu: username

con1: user's password

tipus: user type (roles for permissions within the program)

DATABASE (The table)

This is what I get when trying to save information

This is the form in which I keep the information

the combo I keep it like that

public void tipUsu(){
if(tip_usu1.getSelectedItem()=="...")
{
JOptionPane.showMessageDialog(null, "Ingrese el tipo de usuario");
}
else if(tip_usu1.getSelectedItem()=="usuario")
{
tipus="usuario";
}
else if(tip_usu1.getSelectedItem()=="administrador")
{
tipus="administrador";
}

then the combo is called "tip_usu1" but it's only to know what kind of user it is because what I send to the database is "tipus"

and for the passwords to validate them two

private boolean isPasswordCorrect(char[] con1,char[] con2){
boolean valor = true;
int puntero = 0;
if (con1.length != con2.length){
valor = false;
}  
else{
while((valor)&&(puntero < con1.length)){
if (con1[puntero] != con2[puntero]){
valor = false;
}
puntero++;
}
}
return valor;
}

the two fields of password is only to confirm that it is not wrong to enter the one that I send to the database in "con1" "con2" is only to compare it and see that it's the same

    
asked by Carlos Atehortúa 30.12.2016 в 18:18
source

5 answers

4

You receive a NullPointerException because con is at null in the following statement:

sql=conn.con.prepareStatement("insert into usuario (id_usu,nom_usu,con_usu,tip_usu) values ("+num_usu+",'"+nom_usu+"','"+con1+"','"+tipus+"')");

And the reason why con is at null is because an exception occurred in the Conectar() method, so the variable con was never assigned.

You may notice this because you received the following message from the Conectar() method:

  

com.mysql.jdbc.Driver error

Trsitemente, that message is incomplete. But it is very likely that if you had allowed the original exception to be seen with all the details, you would have noticed that you are actually receiving:

  

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

So the basic problem is that you do not find that class. Have you included in your project the JDBC driver for MySQL ?

Beware of handling exceptions

The fact that the real problem is obscured by the NullPounterException that you received should serve as a lesson that it is not good practice to catch exceptions, print half the details, and try to continue the program. And I notice that you do this in other places of your program too. This is not a good idea and it is very difficult to diagnose the problems correctly.

In this case, the correct thing would have been to not catch the exception at all (remove try-catch and allow the exception to go up to main() ). Sadly, in Java, this implies that you must modify the definition of the methods to include the clause throws XXXException where necessary.

If you do not like doing this, an acceptable alternative is to catch the exception and re-launch it within RuntimeException :

try {
    // ...
} catch (Exception ex) {
    throw new RuntimeException(ex);
}

No matter what you choose, do not try to trap and hide exceptions that you can not really handle.

Additional suggestions to avoid more problems

  • Avoid global variables when they are not necessary. Useful reference: Why is it considered bad practice to use global variables? .
  • Do not concatenate values directly into your SQL string. Learn how to use parameters using the class PreparedStatement .
  • answered by 03.01.2017 в 17:06
    3

    On one of these two lines:

           Class.forName(controlador);
           con=DriverManager.getConnection(db,usuario,password);
    

    An exception occurs. Which you ignore, printing only the message of the exception, here:

       catch(Exception ex)
       {
        System.out.println("Error "+ex.getMessage());
       } 
    

    The Guardar method needs a SUCCESSFUL CONNECTION, which has not occurred.

    As a first step to diagnose the error, change (or add) the previous println by:

        ex.printStackTrace();
    

    This will allow you to know in which line exactly the error occurs. This way you will know if the problem is that the class loader does not find the JDBC driver or if the problem is that the connection fails.

    Or, even better, treat the exception appropriately instead of ignoring it.

        
    answered by 05.01.2017 в 09:31
    0

    The code can be optimized enough, but let's go, the first thing is that you have misused the PreparedStatement. The prepared statement is used because it improves security when making queries about the database, so you do not have to pass the values like this, it would be something like this:

    conn.Conectar();
    sql=conn.con.prepareStatement("insert into usuario(id_usu,nom_usu,con_usu,tip_usu) values(?,?,?,?)");
    sql.setInt(1,id_usu);
    sql.setString(2,nom_usu);
    sql.setString(3,con_usu);
    sql.setString(4,tip_usu);
    sql.executeUpdate();
    conn.cerrar();
    

    Anyway, the error gives you when it comes to connecting to the database, you should debugge or put some println to let you know where it fails.

        
    answered by 05.01.2017 в 10:23
    0

    I'll be able to different solutions I hope one helps you.

    1.- You can paste the file mysql-connector-java.jar Download the driver in the Java configuration instead of adding it to each project that is created. Paste it in C: \ Program Files \ Java \ jre7 \ lib \ ext or where you want java installed.

    2.- Download the file mysql-connector-java.jar Download and paste into the folder within your project ../ WEB-INF / lib note that some WEB-INF folder does not contain any folder of the lib , at that point you must manually create the lib folder and the MySQL connector you must paste it into that folder and this should work.

    3.- Insert this line: DriverManager.registerDriver(new com.mysql.jdbc.Driver()); before receiving the JDBC connection.

        
    answered by 06.01.2017 в 16:37
    -3

    KEEP CLASS:

    package clasesAdministrador;
    
    import Conexion.Conexion1;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.table.DefaultTableModel;
    import formAdministrador.usuarios1ad;
    import javax.swing.JOptionPane;
    
    public class usuario1ad {
        //INICIALIZAR EL OBJETO VACÍO
        Conexion1 conn = new Conexion();
        public PreparedStatement sql;
        public ResultSet datos, rs;
        DefaultTableModel tabla = new DefaultTableModel();
        Statement sent;
    
        public void Guardar(int num_usu, String nom_usu, String con1,String tipus{
            try{
                conn.Conectar();
                sql=conn.con.prepareStatement("insert into usuario   (id_usu,nom_usu,con_usu,tip_usu) values ("+num_usu+",'"+nom_usu+"','"+con1+"','"+tipus+"')");
                sql.execute();
                conn.cerrar();
            }catch(SQLException ex){
              System.out.println("ERROR AL GUARDAR...");
            }
        } // FIN METODO GUARDAR  
    } // FIN DE TODO
    

    CONNECTION CLASS

    package Conexion;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    public class Conexion1{
        public PreparedStatement sql; 
        public ResultSet datos;   
        public Connection con=null;  
    
        //CREAR CONSTRUCTOR VACÍO
        public void Conexion1(){
        }
    
        public void Conectar(){
           String db="jdbc:mysql://localhost:3306/sena";
           String usuario="root";
           String password="salomeaa";
           try{
               String controlador="com.mysql.jdbc.Driver";
               System.out.println("CONEXION CON BASE DE DATOS...." +db);
               Class.forName(controlador);
               con=DriverManager.getConnection(db,usuario,password);
               System.out.println("CONEXION EXITOSA");
           }catch(Exception ex){
               System.out.println("Error "+ex.getMessage());
           } 
        }
    
        public void cerrar(){
            if(con==null){
                try{ 
                   con.close();
                }catch(Exception ex){
                }
            }
        }
    }
    

    Exactly in this line:

    Conexion.conexion1 conn=new Conexion.conexion1();
    

    When calling conexion1() it is necessary that you create the empty constructor so that the class can recognize that a new object is being created.

        
    answered by 31.12.2016 в 05:14