0

Tengo un problema que no puedo resolver por que no veo el error. Estoy desarrollando un simple proyecto en C#, cuando ejecuto un procedimiento almacenado de Postgresql (Insert):

pgsqlCommand cmd = new NpgsqlCommand("select insertclientes(" + @idcuenta_corriente + "," +
                "'" + @nombre+ "','" + @apellido + "'," +
                "'" + @domicilio + "'," + @idprovincia + "," +
                "" + @idlocalidad + "," + @idtipo_identificador + "," +
                "" + @numero_identificador + "," + @idcondicion_iva + "," +
                "'" + @email + "'," + @telefono + "," + @idretenciones + "," + @idlistaprecios + ");", Connections());

No se ve reflejado en la base de datos, es decir que no realiza el insert, pero tampoco me muestra algun error. Para ver la salida del programa y imprimir la consola sql realice esto:

  Console.Write("select insertclientes(" + @idcuenta_corriente + "," +
                "'" + @nombre + "','" + @apellido + "'," +
                "'" + @domicilio + "'," + @idprovincia + "," +
                "" + @idlocalidad + "," + @idtipo_identificador + "," +
                "" + @numero_identificador + "," + @idcondicion_iva + "," +
                "'" + @email + "'," + @telefono + "," + @idretenciones + "," + @idlistaprecios + ");");

Me da como resultado:

select insertclientes(1,'dfhsfhdfshsdfhsdf','dfhfhfh','ghfkghfkfgh',0,0,0,444,0,'hkjhkhjkhgjk',111,2,2);El programa '[15836] Contable1.exe: Seguimiento de programa' terminó con código 0 (0x0).

Ahora si copio la consulta y la esjecuto desde PgAdmin se inserta satisfactoriamente el dato.

Paso el script completo de la capa datos:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//contableEntidad
using System.Windows;
using contableEntidad;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using Npgsql;

namespace contableDatos
{
    public class DContable
    {

        public NpgsqlConnection Connections() {


            var stringConnection = "Server=127.0.0.1;Port=5432;User Id=postgres;Password=admin;Database=contable";
            NpgsqlConnection SQLPostgres = new NpgsqlConnection(stringConnection);

            if (!string.IsNullOrWhiteSpace(stringConnection))
            {

                try
                {

                    SQLPostgres = new NpgsqlConnection(stringConnection);
                    SQLPostgres.Open();
                    Console.WriteLine("conectado ");

                }
                catch (Exception)
                {
                    SQLPostgres.Close();
                    Console.WriteLine("NO conectado ");
                }
            }

            return SQLPostgres;

        }
        //Listar clientes
        public DataTable  Clientes() {

            //NpgsqlDataAdapter dataContable = new NpgsqlDataAdapter("select listarclientes()", SQLPostgres);
            //NpgsqlCommand cmd = new NpgsqlCommand("SELECT * from cliente", Connections());
            //cmd.CommandType = CommandType.StoredProcedure;
            NpgsqlDataAdapter Da = new NpgsqlDataAdapter("SELECT * from cliente", Connections());
            DataTable Dt = new DataTable();
           // DataSet ds = new DataSet();
            Da.Fill(Dt);
            return Dt;

        }

        //Listar 
        public List<Paises> Paiseslist()
        {

            List<Paises> _lista = new List<Paises>();
           // List<string> listaPaises = new List<string>();

            NpgsqlCommand cmd = new NpgsqlCommand("SELECT  * FROM pais", Connections());
            ///// //cmd.CommandType = CommandType.StoredProcedure;

            NpgsqlDataAdapter Da = new NpgsqlDataAdapter("SELECT  * FROM pais", Connections());

            NpgsqlDataReader _reader = cmd.ExecuteReader();

            DataTable Dt = new DataTable();

            DataSet ds = new DataSet();

            Da.Fill(Dt);


            for (var i = 0; _reader.Read(); i++) {

                //listaPaises.Add(_reader[0].ToString());
                Paises paises = new Paises();
                paises.codigo = _reader.GetInt32(0);
                paises.pais = _reader.GetString(1);

                // listaPaises.Add(_reader[2].ToString());

                _lista.Add(paises);

            }
            return _lista;
            //return listaPaises;


        }
        //Listar identificador

        public List<Tidentificacion> TipoIdentificador()
        {
            List<Tidentificacion> _lista = new List<Tidentificacion>();
            NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM public.tipo_identificador", Connections());
            NpgsqlDataReader _reader = cmd.ExecuteReader();

            for (var i = 0; _reader.Read(); i++)
            { 
                Tidentificacion tidenti = new Tidentificacion();
                tidenti.idtipo_identificacion = _reader.GetInt32(0);
                tidenti.identificador = _reader.GetString(1);
                _lista.Add(tidenti);
            }
            return _lista;
        }
        //Listar codigo de iva

        public List<Codigoiva> codigoIVA()
        {
            List<Codigoiva> _lista = new List<Codigoiva>();
            NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM public.codiva", Connections());
            NpgsqlDataReader _reader = cmd.ExecuteReader();

            for (var i = 0; _reader.Read(); i++)
            {
                Codigoiva civa = new Codigoiva();
                civa.codigo_iva = _reader.GetInt32(0);
                civa.descripcion_iva = _reader.GetString(1);
                _lista.Add(civa);
            }
            return _lista;
        }
        //localidad
        public List<Localidad> listLocalidad()
        {
            List<Localidad> _lista = new List<Localidad>();
            NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM public.localidad", Connections());
            NpgsqlDataReader _reader = cmd.ExecuteReader();

            for (var i = 0; _reader.Read(); i++)
            {
                Localidad llocalidad = new Localidad();
                llocalidad.idlocalidad = _reader.GetInt32(0);
                llocalidad.cod_descripcion = _reader.GetString(1);
                _lista.Add(llocalidad);
            }
            return _lista;
        }
        //provincia
        public List<Provincia> listProvincia()
        {
            List<Provincia> _lista = new List<Provincia>();
            NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM public.provincia", Connections());
            NpgsqlDataReader _reader = cmd.ExecuteReader();

            for (var i = 0; _reader.Read(); i++)
            {
                Provincia lprovincia = new Provincia();
                lprovincia.id_provincia = _reader.GetInt32(0);
                lprovincia.provincia = _reader.GetString(1);
                _lista.Add(lprovincia);
            }
            return _lista;
        }

        public void insertClient(
            int idcuenta_corriente,
            string nombre,
            string apellido,
            string domicilio,
            int idprovincia,
            int idlocalidad,
            int idtipo_identificador,
            int numero_identificador,
            int idcondicion_iva, 
            string email, 
            int telefono, 
            int idretenciones, 
            int idlistaprecios) {

            NpgsqlCommand cmd = new NpgsqlCommand("select insertclientes(" + @idcuenta_corriente + "," +
                "'" + @nombre+ "','" + @apellido + "'," +
                "'" + @domicilio + "'," + @idprovincia + "," +
                "" + @idlocalidad + "," + @idtipo_identificador + "," +
                "" + @numero_identificador + "," + @idcondicion_iva + "," +
                "'" + @email + "'," + @telefono + "," + @idretenciones + "," + @idlistaprecios + ");", Connections());
            //cmd.CommandType = CommandType.StoredProcedure;

            Console.Write("select insertclientes(" + @idcuenta_corriente + "," +
                "'" + @nombre + "','" + @apellido + "'," +
                "'" + @domicilio + "'," + @idprovincia + "," +
                "" + @idlocalidad + "," + @idtipo_identificador + "," +
                "" + @numero_identificador + "," + @idcondicion_iva + "," +
                "'" + @email + "'," + @telefono + "," + @idretenciones + "," + @idlistaprecios + ");");
        }

    }
 }

Para el que no quiera ver el script completo este es el método que utilizo para realizar el insert con el procedimiento.

 public void insertClient(
            int idcuenta_corriente,
            string nombre,
            string apellido,
            string domicilio,
            int idprovincia,
            int idlocalidad,
            int idtipo_identificador,
            int numero_identificador,
            int idcondicion_iva, 
            string email, 
            int telefono, 
            int idretenciones, 
            int idlistaprecios) {

            NpgsqlCommand cmd = new NpgsqlCommand("select insertclientes(" + @idcuenta_corriente + "," +
                "'" + @nombre+ "','" + @apellido + "'," +
                "'" + @domicilio + "'," + @idprovincia + "," +
                "" + @idlocalidad + "," + @idtipo_identificador + "," +
                "" + @numero_identificador + "," + @idcondicion_iva + "," +
                "'" + @email + "'," + @telefono + "," + @idretenciones + "," + @idlistaprecios + ");", Connections());
            //cmd.CommandType = CommandType.StoredProcedure;

            Console.Write("select insertclientes(" + @idcuenta_corriente + "," +
                "'" + @nombre + "','" + @apellido + "'," +
                "'" + @domicilio + "'," + @idprovincia + "," +
                "" + @idlocalidad + "," + @idtipo_identificador + "," +
                "" + @numero_identificador + "," + @idcondicion_iva + "," +
                "'" + @email + "'," + @telefono + "," + @idretenciones + "," + @idlistaprecios + ");");
        }

    }
2
  • 1
    Perdone, pero: insertclientes ¿es un procedimiento almacenado?. Le recomiendo 2 cosas: 1) En una variable string escriba la sentencia SQL a ejecutar "INSERT, stored procedured, etc". y muéstrela en consola - puede que tenga errores tipográficos, 2) use try/catch para capturar los detalles del error. Mira cómo usar el try/catch. el 6 ago. 2018 a las 16:02
  • Algo muy importante, inserta los parámetros de tu consulta usando el cmd.Parameters es una muy buena costumbre y te evitaras problemas de seguridad
    – ElGerar
    el 7 ago. 2018 a las 6:05

1 respuesta 1

1

Primero no hay objeto que inicialice la conexión por eso es posible que el query no se ejecute,ademas los parámetros con @ no están siendo comparados con los definidos en el método,reo que podrías llamar de forma implícita los parámetros que estas definiendo en el método

  public void insertClient(
            int idcuenta_corriente,
            string nombre,
            string apellido,
            string domicilio,
            int idprovincia,
            int idlocalidad,
            int idtipo_identificador,
            int numero_identificador,
            int idcondicion_iva, 
            string email, 
            int telefono, 
            int idretenciones, 
            int idlistaprecios) {

            NpgsqlCommand cmd = new NpgsqlCommand("select insertclientes(" + idcuenta_corriente+ "," +
                "'" + nombre+ "','" + apellido + "'," +
                "'" + domicilio + "'," + idprovincia + "," +
                "" + idlocalidad + "," + idtipo_identificador + "," +
                "" + numero_identificador + "," + idcondicion_iva + "," +
                "'" + email + "'," + telefono + "," + idretenciones + "," + idlistaprecios + ");", Connections());
            cmd.CommandType = CommandType.StoredProcedure;
          NpgsqlDataReader pgreader = cmd.ExecuteReader();
        }

    }

En caso quieras usar el @parametroX tendrías que agregar unas lineas mas donde dices ("@paramatroX",parametro) ejemplo:

cmd.Parameters.AddWithValue("@nombre", nombre);

Luego debes poner un ibjeto de Npgsql para que ejecute el query.

NpgsqlDataReader pgreader = cmd.ExecuteReader();

Hay un problema parecido solucionado en este link: https://stackoverflow.com/questions/46112835/execute-stored-procedure-with-parameters-postgresql

1
  • Excelente explicación!!! @Hans Rolando Ramos el 6 ago. 2018 a las 17:24

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.