Conexión con mysql
Publicado por Giuseppe (4 intervenciones) el 27/07/2019 16:33:29
Buen día agradezco su ayuda , estoy aprendiendo a programar en Java , anteriormente programaba en VB, llege al estudio de conexión con base de datos (mysql) siguiendo un ejemplo me conseguí con el siguiente error, agardezco si me pueden orientar en que estoy haciendo mal .
Deleting: C:\Users\valva\Documents\NetBeansProjects\SQL\build\built-jar.properties
deps-jar:
Updating property file: C:\Users\valva\Documents\NetBeansProjects\SQL\build\built-jar.properties
Compiling 2 source files to C:\Users\valva\Documents\NetBeansProjects\SQL\build\classes
C:\Users\valva\Documents\NetBeansProjects\SQL\src\app\conexion.java:105: error: unreported exception SQLException; must be caught or declared to be thrown
con = (Connection) DriverManager.getConnection(URL, USERNAME, PASSWORD);
1 error
C:\Users\valva\Documents\NetBeansProjects\SQL\nbproject\build-impl.xml:955: The following error occurred while executing this line:
C:\Users\valva\Documents\NetBeansProjects\SQL\nbproject\build-impl.xml:295: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at app.conexion.jButton1ActionPerformed(conexion.java:82)
at app.conexion.access$000(conexion.java:20)
at app.conexion$1.actionPerformed(conexion.java:50)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
Hay mas errores.
A continuación el código:
package app;
import static app.conexion.getConection;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author gpbrandi
*/
public class conexion extends javax.swing.JFrame {
public static final String URL = "jbdc:mysql://localhost:3306/Escuela";
public static final String USERNAME = "root";
public static final String PASSWORD = "mysql";
private static void cach() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public conexion() {
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() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("CONECTAR");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(148, 148, 148)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(101, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(107, 107, 107)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = null;
con = getConection();
PreparedStatement ps;
ResultSet res;
ps = con.prepareStatement("select * from persona");
res = (ResultSet) ps.executeQuery();
if(res.next()){
JOptionPane.showMessageDialog(null, resgetString("nombre") + " " + res.getString("domicilio"));
} else {
JOptionPane.showMessageDialog(null,"No Existe Datos");
}
con.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
public static Connection getConection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.driver");
con = (Connection) DriverManager.getConnection(URL, USERNAME, PASSWORD);
JOptionPane.showMessageDialog(null, "Conexion EXITOSA");
} catch (ClassNotFoundException e) {
System.out.println(e);
}
return con;
}
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.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(conexion.class.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 conexion().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
private String resgetString(String nombre) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Deleting: C:\Users\valva\Documents\NetBeansProjects\SQL\build\built-jar.properties
deps-jar:
Updating property file: C:\Users\valva\Documents\NetBeansProjects\SQL\build\built-jar.properties
Compiling 2 source files to C:\Users\valva\Documents\NetBeansProjects\SQL\build\classes
C:\Users\valva\Documents\NetBeansProjects\SQL\src\app\conexion.java:105: error: unreported exception SQLException; must be caught or declared to be thrown
con = (Connection) DriverManager.getConnection(URL, USERNAME, PASSWORD);
1 error
C:\Users\valva\Documents\NetBeansProjects\SQL\nbproject\build-impl.xml:955: The following error occurred while executing this line:
C:\Users\valva\Documents\NetBeansProjects\SQL\nbproject\build-impl.xml:295: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 0 seconds)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at app.conexion.jButton1ActionPerformed(conexion.java:82)
at app.conexion.access$000(conexion.java:20)
at app.conexion$1.actionPerformed(conexion.java:50)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
Hay mas errores.
A continuación el código:
package app;
import static app.conexion.getConection;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author gpbrandi
*/
public class conexion extends javax.swing.JFrame {
public static final String URL = "jbdc:mysql://localhost:3306/Escuela";
public static final String USERNAME = "root";
public static final String PASSWORD = "mysql";
private static void cach() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public conexion() {
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() {
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("CONECTAR");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(148, 148, 148)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(101, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(107, 107, 107)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(140, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = null;
con = getConection();
PreparedStatement ps;
ResultSet res;
ps = con.prepareStatement("select * from persona");
res = (ResultSet) ps.executeQuery();
if(res.next()){
JOptionPane.showMessageDialog(null, resgetString("nombre") + " " + res.getString("domicilio"));
} else {
JOptionPane.showMessageDialog(null,"No Existe Datos");
}
con.close();
} catch (SQLException ex) {
System.out.println(ex);
}
}
public static Connection getConection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.driver");
con = (Connection) DriverManager.getConnection(URL, USERNAME, PASSWORD);
JOptionPane.showMessageDialog(null, "Conexion EXITOSA");
} catch (ClassNotFoundException e) {
System.out.println(e);
}
return con;
}
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.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(conexion.class.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 conexion().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
// End of variables declaration
private String resgetString(String nombre) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Valora esta pregunta


0