Error in DateTime attribute in C # writing to MySQL

2

I am trying to insert into MySQL database the date of birth of the user, in C # the attribute date_match is of type DateTime and in MySQL the attribute date_match is of type Date , to insert C # I am doing doing so:

DateTime nascimento = Convert.ToDateTime(txNascimento.Text);
bDep.Data_nascimento = nascimento;

Obs :. bDep is the base class of the dependent

And in the dependent data class I'm inserting like this:

public void insertDependente (BDependente bDep) {
      string sql = "INSERT INTO dependente(id_funcionario, nome, grau_parentesco, data_nascimento) ";
             sql += "VALUES ("+bDep.Funcionario.Id_funcionario+", '"+bDep.Nome+"', '"+bDep.Grau_parentesco+"', '"+bDep.Data_nascimento+"')";
            conn.update(sql);
        }

I'm selecting like this:

string sql = "SELECT id_dependente, id_funcionario, nome, grau_parentesco, data_nascimento ";
       sql += "FROM dependente";
                while (mdr.Read()) {
                    BDependente bDepe = new BDependente();
                    bDepe.Id_dependente      = mdr.GetInt16("id_dependente");
                    bDepe.Funcionario.Id_funcionario = mdr.GetInt16("id_funcionario");
                    bDepe.Nome               = mdr.GetString("nome");
                    bDepe.Grau_parentesco    = mdr.GetString("grau_parentesco");
                    bDepe.Data_nascimento    = mdr.GetDateTime("data_nascimento");
                    lDep.Add(bDepe);
                }

Whenever I register a new dependent on the database it looks like this:

ThefirstrecordwasmadeinMySQLitself,andeventhenwhenIlookinC#itbringsthetimeandwhenIlookinC#theotherdependent,thisothererrorappears:

    
asked by anonymous 28.04.2016 / 13:34

1 answer

4

The problem starts with recording. This is not the way to do it. It has a huge security problem in doing this besides generating this type of problem.

So I understand the error in reading occurs because the recording failed.

I would have to change to something like this:

var sqlInsert = new SqlCommand(@"Insert into dependente (id_funcionario, nome, grau_parentesco, data_nascimento)
                    VALUES (@id_funcionario, @nome, @grau_parentesco, @data_nascimento)", conn);
sqlInsert.Parameters.AddWithValue("@id_funcionario", bDep.Funcionario.Id_funcionario);
sqlInsert.Parameters.AddWithValue("@nome", bDep.Nome);
sqlInsert.Parameters.AddWithValue("@grau_parentesco", bDep.Grau_parentesco);
sqlInsert.Parameters.AddWithValue("@data_nascimento", bDep.Data_nascimento.ToShortDateString());
sqlInsert.ExecuteNonQuery();

There you will adapt to your need. And please, never try to record this way again.

Ideally, you should not use variables with Hungarian notation as well

I'm not the fate of the term attribute, I prefer field .

    
28.04.2016 / 14:10