How to insert a date with c # and MySQL in reverse format?

0

My database is designed in such a way that the insertion of dates is under the format years / months / days and when sending the content of that control by means of c # to the database, I do not know of the appropriate sentence for convert it and send it under that same format. This data I am capturing through a DataTimePicker

string agregar = "insert into values('" + txtIDUsuario.Text + "'," + "md5('" + TxtContraseña.Text + "'), 'md5',' " + Convert.ToInt16(txtTiposUsuario) + "','" + txtNombresUsuarios.Text + "','" + txtApellidosUsuario.Text + "';'" + Convert.ToDateTime(dataTFNacimiento.Value) + "','" + Convert.ToInt16(txtNumeroUsuario) + "','" + txtCorreoUsuario.Text + "','" + rtxtRedSocialUsuario.Text + "','" + rtxtDireccionUsuario.Text + "');";

There is the complete line of code.

    
asked by Gabriel Hernández 06.11.2016 в 02:59
source

2 answers

2

The problem here is that you are concatenating the values directly into your insert. This is not a good habit for different reasons.

A reason that is often heard, but it is always good to repeat it, is that it exposes you to the SQL injection .

Another reason is that it forces you to manipulate the values as strings, even though it makes no sense to do so. And that is the case here. Your value is a date, so it does not make sense that you have to worry about formatting it correctly to insert it in a date field in your database (I assume that the field in your database is of type date .) If not, maybe you have another problem there too).

The correct way to insert a date from a DataTimePicker is by using parameters.

Since you have not described your table, let me give you a simplified example.

Assuming you have a table defined this way:

create table tbl (
    dt date
);

Inserting in this table from C # using a date that comes from a DataTimePicker would look like the following:

string insertText = "insert into tbl (dt) values (@dt)";
using (var cmd = new MySqlCommand(insertText, conn))
{
    cmd.Parameters.AddWithValue("@dt", dateTimePicker1.Value);
    cmd.ExecuteNonQuery();
}

As you can see, by using a parameter, I can pass the date directly from dateTimePicker1.Value without having to worry about formatting a string.

Ideally, you should use parameters with the other values of your insert as well.

Useful reference: Working with Parameters .

    
answered by 06.11.2016 в 04:26
1

You can give you the desired format by toString , that value you would send to the query directly.

string fecha = dataTFNacimiento.Value.ToString("yyyyMMdd");
    
answered by 06.11.2016 в 03:28