I cannot enter the Datetime fields in the sql database

Asked

Viewed 207 times

0

I can’t enter in the fields dateCreation and dataRefMovimento in the sql database

     private Contexto contexto;
    public void Inserir(RegCabecalho regCabecalho)
    {       
        var strQuery = "";
        strQuery += " INSERT INTO regCabecalho (tipoReg, dataCriacao,horaCriacao,dataRefMovimento,IDArq,codParceiro
      ,numeroSeq,versaoLayout) ";
      strQuery += string.Format(" VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}') " ,
      regCabecalho.tipoReg, regCabecalho.dataCriacao,
      regCabecalho.horaCriacao, regCabecalho.dataRefMovimento, regCabecalho.IDArq,
      regCabecalho.codParceiro,
      regCabecalho.numeroSeq, regCabecalho.versaoLayout
            );
        using (contexto = new Contexto())
        {
            contexto.ExecutaComando(strQuery);
        }
    }
  • 2

    "I can’t" it’s too vague. What happens? Does it make a mistake? Without this information it’s hard for anyone to help you.

  • 1

    What is the error message?

  • 1

    Which database? are you using Entity Framework? where are you passing your Datetime field? what is Regcabecalho for ?

  • suggestion, always enter the date in the format'yyyymmdd' example '20171201'

1 answer

1


1. Use any data access library

Entity Framework, Dapper, something, but do not write SQL in hand. Concatenating data in hand in the middle of SQL leaves you open security problems and makes its application difficult to maintain after.

2. Dates not universally represented in databases

You have to deliver dates in the pattern that the database expects, usually a formatted string in a specific way. You are concatenating the data in hand, which generates the date in a string format, but which may not be the format the database is waiting for.

Your computer is probably formatting dates in the day/month/year scheme, but the database is waiting in American format (month/day/year) or in ISO 8601 format.

Create the class below somewhere ...

public static class DateExtensions
{
    public static string ToIso8601Date( this DateTime date )
    {
        return date.ToString( "yyyy-MM-dd" );
    }
}

... and add ToIso8601Date() at the end of regCabecalho.dataCriacao and regCabecalho.dataRefMovimento. See if it works and then comment there.

  • Thanks! I have succeeded

  • You’re welcome, and I’m glad you did. But seriously, think about switching from manual SQL to a database access API. This problem you had with date probably goes to numbers with decimals (comma vs dot) and strings with quotes, apostrophes... Things that don’t occur with database Apis where you don’t write SQL.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.