How to insert separate data?

Asked

Viewed 57 times

1

I want to insert data into a table in the database, but there are no mandatory fields, how should I proceed with this, because I can’t perform the command this way for example:

            MySqlCommand command = new MySqlCommand("INSERT INTO item VALUES( " +
                    "@id_item, " +
                    "@nome, " +
                    "@descricao, " +
                    "@imagem, " +
                    "@categoria); ",conexao)

For example the field descricaoit is not mandatory, if it is empty I can not send the data to the bank, how could solve this?

2 answers

3


You can add the description column conditionally, that is, only if your variable representing the description value is filled in that we will insert the data in the column.

MySqlCommand command = new MySqlCommand("INSERT INTO item (id_item, " +                                                                                          
                                                          "nome, " +
                                                          (!string.IsNullOrWhiteSpace(descricao) ? "descricao, " : "") +
                                                          "imagem, " +
                                                          "categoria, " +
                                              "VALUES(@id_item, " +
                                                     "@nome, " +
                                                     (!string.IsNullOrWhiteSpace(descricao) ? "@descricao, " : "") +
                                                     "@imagem, " +
                                                     "@categoria); ", conexao);

In this example I considered that its variable is called descricao.

  • Thank you so much for helping me!

0

If you want to use a lighter layer to work with the bank, that is, use ADO directly, I suggest using the Dapper. It’s just a wrapper for ADO, but with some features and extensions that can help you.

Browser other questions tagged

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