Foros del Web » Programación para mayores de 30 ;) » Java »

Insertar en DB mysql con java

Estas en el tema de Insertar en DB mysql con java en el foro de Java en Foros del Web. hola ... quiero insertar datos que capto desde un formulario con un boton este es mi codigo, me devuelve este error: java.lang.NullPointerException // FormInsertarDatos.java package ...
  #1 (permalink)  
Antiguo 17/09/2012, 17:27
 
Fecha de Ingreso: septiembre-2012
Mensajes: 1
Antigüedad: 11 años, 7 meses
Puntos: 0
Insertar en DB mysql con java

hola ...
quiero insertar datos que capto desde un formulario con un boton este es mi codigo, me devuelve este error:
java.lang.NullPointerException

// FormInsertarDatos.java
package inicio;


public class FormInsertar extends javax.swing.JFrame {


public FormInsertar() {
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() {

jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);

jLabel1.setText("jLabel1");

jButton1.setText("REGISTRAR");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton1MouseClicked(evt);
}
});

jLabel2.setText("NOMBRE");

jLabel3.setText("SUELDO");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, layout.createSequentialGroup()
.addGap(99, 99, 99)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.Component Placement.RELATED, 70, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(84, 84, 84))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.TRAILING, false)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
.addComponent(jTextField1))
.addGap(111, 111, 111))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_S IZE, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(154, 154, 154))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(28, 28, 28)
.addComponent(jButton1)
.addContainerGap(32, Short.MAX_VALUE))
);

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

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

try{
RegistrarDatos mRegistrar=new RegistrarDatos();
mRegistrar.MetodoRegistrar(jTextField1.getText() ,jTextField2.getText());
}
catch(Exception e)
{
System.out.println(e);
}


// TODO add your handling code here:
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClass Name());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FormInsertar.cl ass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FormInsertar.cl ass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FormInsertar.cl ass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FormInsertar.cl ass.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FormInsertar().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}

//RegistrarDatos.java
package inicio;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class RegistrarDatos {
String nombre, sueldo;
String user,pass,db,url,driver,sql;
Connection conn; Statement stmt;


public RegistrarDatos(){
this.user="root";this.pass="1234santiago";this.db= "inicioj";
this.url = "jdbc:mysql://localhost:3307/" ;
this.driver = "com.mysql.jdbc.Driver" ;
this.conn = null ;

}
public void MetodoRegistrar (String nombre , String sueldo) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException
{
this.nombre=nombre;
this.sueldo=sueldo;

System.out.println ( "MySQL Connect Example." ) ;


try {
Class.forName ( driver ) .newInstance () ;
conn = DriverManager.getConnection ( url+db,user,pass ) ;
sql = "INSERT INTO contactos (Nombre,Sueldo) VALUES ("+"'"+this.nombre+"','"+this.sueldo+"')";
JOptionPane.showMessageDialog(null,this.nombre+" "+this.sueldo);
stmt.execute(sql);


}
catch ( SQLException ex )
{
Logger.getLogger(FormInsertar.class.getName()).log (Level.SEVERE, null, ex);
System.out.println(ex);
}
}
}
  #2 (permalink)  
Antiguo 18/09/2012, 01:09
Avatar de chuidiang
Colaborador
 
Fecha de Ingreso: octubre-2004
Mensajes: 3.774
Antigüedad: 19 años, 7 meses
Puntos: 454
Respuesta: Insertar en DB mysql con java

Hola:

Normalmente cuando se muestra una excepción (java.lang.NullPointerException en tu caso), java suele indicar el fichero java y la línea exacta en que se produce la excepción. Ayudaría si nos dijeras en todo ese montón de código cual es la línea concreta que da la excepción.

Se bueno.
__________________
Apuntes Java
Wiki de Programación

Etiquetas: mysql, string
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:34.