Insert into database in C#

Asked

Viewed 69 times

-3

I’m a beginner in the area and I need to make a select in two tables of the SQL server database through C#, as shown below:

("INSERT INTO entrada_2(id_entrada, id_saida, descricao_entrada, data, valor_entrada)" +
    "VALUES('" + Cb_Descricao_Entrada.Text + "', '" + hoje.ToString("yyyy-MM-dd") + "', '" + Txb_Valor_Entrada.Text.Replace(",", ".") + "')", conexao);

My tables:

entradas

id_entrada               int pk       not null
id_saida                 int fk      not null
descricao_entrada        varchar(150) not null
data                     datetime     not null
valor_entrada            varchar(20)  not null
saidas

id_saida                 int pk       not null
descricao_saida          varchar(150) not null
data                     datetime     not null
valor_saida              varchar(20)  not null

When I execute insert error and does not let do the insert and says that the columns are unequal.

Thank you from now on for anyone who can help me. Thank you

  • Just count the number of fields you placed in parentheses after the table name (entrada_2) [5] and the amount of values you put in the VALUES clause [3]. Quantities need to be equal.

  • Thanks for the help

  • My doubt is my table has [5] items to insert, of these [5] one is pk and the other fk, how do I reference - them in the form of my application? hide them in error Insert, and put them too!

  • If in the definition of your table PK has specified a default value then you can omit both the field name and the value, if you do not have a default value then it is mandatory that you enter a value. As for FK you have to inform which record of the table referenced this row being included this related and therefore it is mandatory to specify a value, your application is that you have to know which value to inform, remembering that the corresponding record must already exist in the related table.

  • Thanks for your help. VLW

  • Your model is wrong because the way it is there, you need to have exits before entrances.

Show 1 more comment

1 answer

0

The insert of your table must contemplate the fields of the same.

If Id is auto-increment, just leave the space for it. Look at this question that addresses this here: Question of Auto-increment

Another point, your FK, should already exist. If you have questions about FK see: Question about FK

In case your idea of Fk, is to fill the output after the input. I recommend to invert your FK, and reference the id_Entrada, in the output table.

  • Thanks for your help. VLW

  • If the answer answered the question, mark it as the right answer.

Browser other questions tagged

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