1

Could someone help me with an Insert ? I'm trying to give insert in the DB but I have to convert the dateTimePicker pro to the right format, I do not know if it is exactly like this, I already tried google and tested it in several ways and none worked for me. The first image is the INSERT, which is in a class. The second image is the own button to insert. The third image is the Database (yes I did in phpmyadmin of wamp msm pq is a very small and simple DB). The error that happens when I try to insert is simply in that throw; Of the insert, and I think it's the question of help. Thank you to anyone who can help. i just cant format the "Datav".

public void inserir_produtov()
    {
        try
        {
            string inserir1 = "INSERT INTO venda VALUES (null, '" + Datav.ToString("yyyy-MM-dd HH:mm:ss") + "', '" +
                                                     Id + "','" +
                                                     Quantidadev + "','" +
                                                     Valorv.ToString().Replace(',', '.') + "');";
            bancodedados1.ExecutarComandos(inserir1);
        }
        catch
        {
            throw;
        }
    }

Here is the Button to insert:

private void btngravar1_Click(object sender, EventArgs e)
    {
        vendas.Id = int.Parse(txtidproduto.Text);
        vendas.Quantidadev = int.Parse(txtquantidade2.Text);
        vendas.Valorv = double.Parse(txtvalor.Text);
        vendas.Datav = DateTime.Parse(dateTimePicker1.Text);

        if (txtidvenda.Text == "")
        {
             vendas.inserir_produtov();
             Limpar();
             MessageBox.Show("Dados inseridos com sucesso.");    
        }

1 Answers1

0

Use parameters instead so you don't need to format. This will also help prevent SQL injection too.

Have a look at this link:

SQL Insert Query Using C#

Community
  • 1
  • 1
James
  • 2,812
  • 3
  • 22
  • 33
  • this program its just for my homework, dont need to prevent from sql injection now. – Paulo Henrique Mar 18 '17 at 00:22
  • Sure, a date might look like this: 2004-05-23T14:25:10.487 – James Mar 18 '17 at 00:26
  • 1
    The date format of your strings is probably different from the format of the database. You need to use parameters so you don't have to convert formats. And you need to prevent SQL injection for homework as well. – Dour High Arch Mar 18 '17 at 00:46