4
respuestas

Error

Buenos días desde ayer al correr mi código para agregar los productos me aparece un error realmente no se como solucionarlo, me prodrian ayudar por favor. este es el error `` Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')VALUES(Vaso,Vaso de cristal,10)' at line 1 at com.alura.jdbc.view.ControlDeStockFrame.guardar(ControlDeStockFrame.java:257)

`public List<Map<String, String >> listar() throws SQLException {
    Connection con = new ConnectionFactory().recuperaConexion();
    Statement statement = con.createStatement();
    
    statement.execute("SELECT ID, NOMBRE, DESCRIPCION, CANTIDAD FROM PRODUCTO");
    ResultSet resultSet = statement.getResultSet();
    List<Map<String, String>>resultado= new ArrayList<>();
    
    while (resultSet.next()){
        Map<String, String > fila = new HashMap<>();
        fila.put("ID",String.valueOf(resultSet.getInt("ID")));
        fila.put("NOMBRE", resultSet.getString("NOMBRE"));
        fila.put("DESCRIPCION", resultSet.getString("DESCRIPCION"));
        fila.put("CANTIDAD",String.valueOf(resultSet.getInt("CANTIDAD")));
        
        resultado.add(fila);
    }
    
    con.close();
    
    return resultado;
}

public void guardar(Map<String, String> producto) throws SQLException {
    Connection con = new ConnectionFactory().recuperaConexion();
    Statement statement = con.createStatement();
    statement.execute("INSERT INTO PRODUCTO(nombre, descripcion, cantidad))"
    + "VALUES('" + producto.get("NOMBRE")+ "','"
    + producto.get("DESCRIPCION")+ "',"
    + producto.get("CANTIDAD")+")",Statement.RETURN_GENERATED_KEYS);
    
    ResultSet resultSet = statement.getGeneratedKeys();
    
    while (resultSet.next()) {
        System.out.println(
                String.format(
                        "Fue insertado el producto de ID %d",
                        resultSet.getInt(1)));
        
    }`
    ` //TODO
    var producto = new HashMap<String, String>();
    producto.put("NOMBRE",textoNombre.getText());
    producto.put("DESCRIPCION",textoDescripcion.getText()); 
    producto.put("CANTIDAD", String.valueOf(cantidadInt));
    
    var categoria = comboCategoria.getSelectedItem();

    try {
        this.productoController.guardar(producto);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

    JOptionPane.showMessageDialog(this, "Registrado con éxito!");

`

4 respuestas

Me aparece exactamente el mismo error y no se como solucionarlo, ayuda pls.

Hola chicos, estaba tratando con el mismo error y me di cuenta que el metodo que usan en el video no es el mejor para manejar Querys, es mejor el metodo de consultas preparadas, es mucho mejor de interpretar y no se presentan tantos errores de syntaxis:

public void guardar(Map<String, String> producto) throws SQLException { Connection con = new CreaConexion().recuperaConexion();

String insertQuery = "INSERT INTO productos (NOMBRE, DESCRIPCION, CANTIDAD) VALUES (?, ?, ?)";

try (PreparedStatement preparedStatement = con.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS)) {
    preparedStatement.setString(1, producto.get("NOMBRE"));
    preparedStatement.setString(2, producto.get("DESCRIPCION"));
    preparedStatement.setInt(3, Integer.parseInt(producto.get("CANTIDAD")));

    preparedStatement.executeUpdate();

    ResultSet resultSet = preparedStatement.getGeneratedKeys();

    while (resultSet.next()) {
        System.out.println(String.format("Fue insertado el producto de ID %d", resultSet.getInt(1)));
    }
}

}}

Aquí, los números 1, 2 y 3 se corresponden con las posiciones de los marcadores de posición en la consulta. Los valores reales se establecen en estas posiciones. Asi no se tienen tantos errores con las comillas y la syntaxis

Muchas gracias Marlon

Tienes un cierre de paréntesis doble en la Query Ingrese aquí la descripción de esta imagen para ayudar con la accesibilidad