Save date in MySQL in c #

0

I'm doing an ABC project in Windows Forms through visual studio, and after several forms I need to save the date, however, at the time of saving the connection is not successful (the connection works well with other forms that do not require the date), the code is as follows:

private void btn_Guardar_Click(object sender, EventArgs e)
    {
        if (alDAO.Agregar(RecuperarInformacion()) == 1)
        {
            MessageBox.Show("Registro Agregado");
        }
        else
        {
            MessageBox.Show("Algo salio mal");
        }
        //Actualiza el grid
        dtg_Vista.DataSource = alDAO.Buscar();
        limpiarcontroles();
    }

public int Agregar(Cls_AlumnosBO alBO)
    {
        //se sustituyen los números por los valores de las variables
        string ComandoSQL = string.Format("INSERT INTO alumno (matricula, nombre, apellido, id_div, fecha_nac)VALUES({0}, '{1}', '{2}', {3}, {4});", alBO.Matricula, alBO.Nombre, alBO.Apellido, alBO.Id_div, alBO.Fecha_nac);
        return MiConexion.EjecutarComando(ComandoSQL);
    }
private Cls_AlumnosBO RecuperarInformacion()
    {
        //Se recupera informacion del formulario
        //crea un objeto de la clase productos bo
        alBO = new Cls_AlumnosBO();
        alBO.Matricula = Convert.ToInt32(txt_matricula.Text);
        alBO.Nombre = txt_Nombre.Text;
        alBO.Apellido = txt_Apellido.Text;
        alBO.Fecha_nac = Convert.ToDateTime(dt_Fecha.Text);
        alBO.Id_div = Convert.ToInt32(cmb_Division.SelectedValue);

        return alBO;
    }
    
asked by GreedSource 11.03.2018 в 03:58
source

1 answer

0

Your error is in this line

string ComandoSQL = string.Format("INSERT INTO alumno (matricula, nombre, apellido, id_div, fecha_nac)VALUES({0}, '{1}', '{2}', {3}, {4});", alBO.Matricula, alBO.Nombre, alBO.Apellido, alBO.Id_div, alBO.Fecha_nac);

This internally calls DateTime.ToString () , which says the following:

  

Converts the value of the current DateTime object to its representation of   equivalent string using the format conventions of the reference   current cultural.

In mine it generates the following:

3/11/2018 3:59:31 AM

Which means it depends on what your program is using as CultureInfo , which is usually based on your system's options.

The easiest thing would be for you to solve using the ToString method that accepts a format to convert the date to a string of characters accepted by mysql as described in the comments. However, I recommend that you do not send the strings directly in your queries but that you use parameterized instructions to reduce the chances of suffering from SQL injection problems.

    
answered by 11.03.2018 / 05:08
source