comment insert dans deux tables de vb.net

je veux insert deux valeurs dans deux tables d'une database sql que j'avais créée. Dans mon code vb.net, mon problème est que si je l'insère, je suis inséré mais seulement dans une autre table, parfois il ne pénètre pas à l'intérieur.

voici mon code que j'avais utilisé:

c = TextBox1.Text sh = TextBox2.Text ph = Val(TextBox3.Text) ad = RichTextBox1.Text ob = Val(TextBox4.Text) con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True") con.Open() str1 = " INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' ) " str2 = "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & ")" cmd = New SqlCommand cmd.Connection = con cmd.CommandType = CommandType.Text cmd.CommandText = str1 cmd.ExecuteNonQuery() cmd.CommandText = str2 cmd.ExecuteNonQuery() MsgBox("ITEM IS INSERTED", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "CUSTOMER ADDED") TextBox1.Clear() TextBox2.Clear() TextBox3.Clear() TextBox4.Clear() TextBox5.Clear() RichTextBox1.Clear() 

Vous pouvez réellement le faire en une seule command et même envelopper dans une transaction comme celle-ci:

 str1 = "begin tran; " str1 &= "INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' ); " str1 &= "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & "); " str1 &= "commit tran; " cmd = New SqlCommand cmd.Connection = con cmd.CommandType = CommandType.Text cmd.CommandText = str1 cmd.ExecuteNonQuery() 

Ensuite, vous devez utiliser try / catch sur une exception SqlServerException pour voir ce qui ne va pas. Quelque chose comme:

 try ' all your sql code catch (sqlex as SqlException) MessageBox.Show(sqlex.Message) 

Lire aussi sur l'injection SQL.

Vous n'avez pas besoin d'utiliser une variable de string différente pour insert les valeurs. Vous pouvez le faire comme ceci:

 str1 = " INSERT INTO CUSTOMER VALUES('" & c & " ' , '" & sh & "' ," & ph & ",'" & ad & "' ,'" & TextBox5.Text & "' );" str1 & = "INSERT INTO BALANCE VALUES ('" & c & "', " & ob & ")" cmd = New SqlCommand cmd.Connection = con cmd.CommandType = CommandType.Text cmd.CommandText = str1 cmd.ExecuteNonQuery()