Java - Problemas de conexión con MySQL

 
Vista:
sin imagen de perfil
Val: 28
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Problemas de conexión con MySQL

Publicado por Arturo (16 intervenciones) el 24/03/2020 04:52:54
Buenas noches

Alguien que me pueda ayudar con este problema que tengo, llevo días intentando conectar Netbeans usando XAMPP a la base creada en MySQL.

Eh probado diferentes códigos y aun así no eh logrado la conexión, espero su ayuda por favor.

Lo que necesito es que el botón guardar pueda hacer esa acción también en la base de datos, pero no logra guardar nada con la conexión.




1.1eeeee


Este es el código de conexión a la base de datos

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
 
/**
 *
 * @author Arturo R C
 */
public class conectarBD {
 
    static Statement sentencia;
    Connection con = null;
 
public Connection Conexion() throws SQLException, ClassNotFoundException {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/proyecto?useSSL=false", "root", "1q2w3e4r5t6y");
        sentencia = (Statement) con.createStatement();
        System.out.println("Conexion exitosa con Base de Datos");
    } catch(SQLException | ClassNotFoundException ex) {
        System.out.println("Error con la conexion de Base de Datos"+ex.getMessage());
    }
    return con;
}
 
}


Y está parte es del menú inventario que pasa al submenú AltasInventario.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
 
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 
/**
 *
 * @author Arturo R C
 */
public class AltasInventario extends javax.swing.JInternalFrame {
    DefaultTableModel modelo;
    conectarBD cc = new conectarBD();
 
    /**
     * Creates new form Altas
     */
    public AltasInventario() {
        initComponents();
        modelo = new DefaultTableModel();
        modelo.addColumn("codigo");
        modelo.addColumn("articulo");
        modelo.addColumn("sucursal");
        modelo.addColumn("existencia");
        modelo.addColumn("marca");
        this.tabladealtas.setModel(modelo);
    }
 
    /**
     * 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();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtcodigoinv = new javax.swing.JTextField();
        txtarticuloinv = new javax.swing.JTextField();
        txtsucursalinv = new javax.swing.JTextField();
        txtexistenciainv = new javax.swing.JTextField();
        txtmarcainv = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabladealtas = new javax.swing.JTable();
        btnguardar = new javax.swing.JButton();
        btnlimpiar = new javax.swing.JButton();
        btneditar = new javax.swing.JButton();
        btnsalir = new javax.swing.JButton();
 
        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Altas Inventario");
 
        jLabel1.setText("codigo");
 
        jLabel2.setText("articulo");
 
        jLabel3.setText("sucursal");
 
        jLabel4.setText("existencia");
 
        jLabel5.setText("marca");
 
        tabladealtas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
 
            },
            new String [] {
                "codigo", "articulo", "sucursal", "existencia", "marca"
            }
        ));
        jScrollPane1.setViewportView(tabladealtas);
 
        btnguardar.setText("GUARDAR");
        btnguardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnguardarActionPerformed(evt);
            }
        });
 
        btnlimpiar.setText("LIMPIAR");
        btnlimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnlimpiarActionPerformed(evt);
            }
        });
 
        btneditar.setText("EDITAR");
 
        btnsalir.setText("SALIR");
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtmarcainv, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)
                            .addComponent(txtexistenciainv)
                            .addComponent(txtsucursalinv)
                            .addComponent(txtarticuloinv)
                            .addComponent(txtcodigoinv))
                        .addGap(60, 60, 60)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnguardar)
                            .addComponent(btnlimpiar)
                            .addComponent(btneditar)
                            .addComponent(btnsalir)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 442, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtcodigoinv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnguardar))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtarticuloinv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnlimpiar))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtsucursalinv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btneditar))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtexistenciainv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnsalir))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtmarcainv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
 
        pack();
    }// </editor-fold>
 
    private void btnlimpiarActionPerformed(java.awt.event.ActionEvent evt) {
        txtcodigoinv.setText("");
        txtarticuloinv.setText("");
        txtsucursalinv.setText("");
        txtexistenciainv.setText("");
        txtmarcainv.setText("");
    }
 
    private void btnguardarActionPerformed(java.awt.event.ActionEvent evt) {
 
        try {
 
            String []info = new String[5];
            info[0]= txtcodigoinv.getText();
            info[1]= txtarticuloinv.getText();
            info[2]= txtsucursalinv.getText();
            info[3]= txtexistenciainv.getText();
            info[4]= txtmarcainv.getText();
            modelo.addRow(info);
 
            txtcodigoinv.setText("");
            txtarticuloinv.setText("");
            txtsucursalinv.setText("");
            txtexistenciainv.setText("");
            txtmarcainv.setText("");
 
            //** Llamamos al objeto conexión, donde se declara una variable donde se conectara a la base de datos de MySQL.
            Connection cn = cc.Conexion();
 
            String codigo, articulo, sucursal, existencia, marca;
            String sql="";
            codigo = txtcodigoinv.getText();
            articulo = txtarticuloinv.getText();
            sucursal = txtsucursalinv.getText();
            existencia = txtexistenciainv.getText();
            marca = txtmarcainv.getText();
            sql="INSERT INTO inventario (codigo, articulo, sucursal, existencia, marca) VALUES (?, ?, ?,?, ?)";
            try {
                PreparedStatement pst = (PreparedStatement) cn.prepareStatement(sql);
                pst.setString(1, codigo);
                pst.setString(2, articulo);
                pst.setString(3, sucursal);
                pst.setString(4, existencia);
                pst.setString(5, marca);
                int n=pst.executeUpdate();
                if (n>0){
                    JOptionPane.showMessageDialog(null, "Registro guardado");
 
                }
            } catch (SQLException ex) {
                Logger.getLogger(AltasInventario.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            Logger.getLogger(AltasInventario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AltasInventario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
 
    // Variables declaration - do not modify
    private javax.swing.JButton btneditar;
    private javax.swing.JButton btnguardar;
    private javax.swing.JButton btnlimpiar;
    private javax.swing.JButton btnsalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabladealtas;
    private javax.swing.JTextField txtarticuloinv;
    private javax.swing.JTextField txtcodigoinv;
    private javax.swing.JTextField txtexistenciainv;
    private javax.swing.JTextField txtmarcainv;
    private javax.swing.JTextField txtsucursalinv;
    // End of variables declaration
 
}

Ahora, este es el error que me sale:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Error con la conexion de Base de DatosUnknown database 'proyecto'
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at Actividad4.AltasInventario.btnguardarActionPerformed(AltasInventario.java:217)
	at Actividad4.AltasInventario.access$000(AltasInventario.java:24)
	at Actividad4.AltasInventario$1.actionPerformed(AltasInventario.java:97)
	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)
	at java.awt.Component.processMouseEvent(Component.java:6539)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
	at java.awt.Component.processEvent(Component.java:6304)
	at java.awt.Container.processEvent(Container.java:2239)
	at java.awt.Component.dispatchEventImpl(Component.java:4889)
	at java.awt.Container.dispatchEventImpl(Container.java:2297)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4904)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4535)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4476)
	at java.awt.Container.dispatchEventImpl(Container.java:2283)
	at java.awt.Window.dispatchEventImpl(Window.java:2746)
	at java.awt.Component.dispatchEvent(Component.java:4711)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:760)
	at java.awt.EventQueue.access$500(EventQueue.java:97)
	at java.awt.EventQueue$3.run(EventQueue.java:709)
	at java.awt.EventQueue$3.run(EventQueue.java:703)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:84)
	at java.awt.EventQueue$4.run(EventQueue.java:733)
	at java.awt.EventQueue$4.run(EventQueue.java:731)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:730)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 12 seconds)


ESPERO SU AYUDA POR FAVOR, GRACIAS.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Problemas de conexión con MySQL

Publicado por Costero (148 intervenciones) el 24/03/2020 05:18:33
Parece que el error te lo esta diciendo. No conoce de base de dato: Proyecto

1
Error con la conexion de Base de DatosUnknown database 'proyecto'
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 28
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Problemas de conexión con MySQL

Publicado por Arturo (16 intervenciones) el 24/03/2020 05:21:53
Pero si existe la base de datos en MySQL


1.3
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Franklin
Val: 456
Bronce
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Problemas de conexión con MySQL

Publicado por Franklin (179 intervenciones) el 24/03/2020 13:20:50
Tienes en tu CLasspath el jar conector java-mysql?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Problemas de conexión con MySQL

Publicado por Costero (148 intervenciones) el 24/03/2020 14:08:29
Si podria ser. Pero quizas el error seria Classnotfound exception o algo asi.

Quizas sea un problema de permission:

1
mysql> GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';

Trata esto:

1
mysql> GRANT ALL PRIVILEGES ON proyecto.* TO 'root'@'localhost';
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 28
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Problemas de conexión con MySQL

Publicado por Arturo (16 intervenciones) el 24/03/2020 15:37:04
SI, si esta integradoen la bibleoteca del java
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar