Format dates in sql

1

I have a program in the c # (Visual Studio) registry that contains a textbox to receive a date. Knowing that SQL writes the date in American format, how can I make the user type the date in Brazilian format and that date can be saved successfully in the bank? In the way I'm doing, the user types the date in Brazilian format, but an error occurs when saving, because SQL is trying to save MM / dd / yyyy. Could someone help me, please? Thanks in advance.

Below the code I'm using:

//Variável que recebe o cast no textbox 
var validaDataVenda = DateTime.Parse(txtDataVenda.Text); 
var validaDataPagto = DateTime.Parse(txtDataPagamento.Text); 

//Comando que insere os dados no banco, recebendo os textboxes como parâmetros
VendaDAO.InsertVenda(novoCodigo.ToString(), txtValor.Text, dataDaVenda.ToString(), dataDoPagamento.ToString(), txtCodigoCliente.SelectedValue.ToString(), txtCodigoProduto.SelectedValue.ToString(), txtQuantidadeRequerida.Text, recebido); 

If I insert "31/102016", for example, this error occurs: "Conversion failed when converting date and / or time from character string".

    
asked by anonymous 21.07.2016 / 13:57

1 answer

0

Although the way you are passing the parameters is not the most appropriate, you should send the data in your data types without a "tostring" and perform the recording according to the method used below.

But if you want to send in text format, better take a look at this article, which explains how you format a date correctly.

link

Now I do not know how your application is, for web I do not recommend inserts into the database without using parameters like in the method below to avoid Sql Injection.

Here is an example of a function that inserts dates that solves your problem

public Boolean Insere(Clientes cadastro)
{
    Conexao banco = new Conexao();
    SqlConnection con = banco.Conectar();

    try
    {
        SqlCommand comando = new SqlCommand(@"INSERT INTO CLIENTES (NOME, EMAIL, TELEFONE, DATANASC) 
            VALUES (@nome, @email, @telefone, @datanasc)", con);

        con.Open();
        comando.Parameters.AddWithValue("@nome", cadastro.Nome);
        comando.Parameters.AddWithValue("@email", cadastro.Email);
        comando.Parameters.AddWithValue("@telefone", cadastro.Telefone);
        comando.Parameters.AddWithValue("@datanasc", cadastro.DataNasc);

        comando.ExecuteNonQuery();
        return true;

    }
    catch (Exception erro)
    {
        return false;
    }
}
    
21.07.2016 / 14:22