Click here to Skip to main content
15,990,892 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,
Please I need your assistance
I would like to fill "commande" and "details de commande" two tables access databaseautomatically using two procedures
1: procedure add commande:
VB
Public Sub AddCommande(ByVal NumCommande As Integer, ByVal DateCommande As Date, ByVal NumCLient As Integer, ByVal Description_Commande As String)
 
        If CN.State = ConnectionState.Closed Then
            CN.Open()
        End If
                Dim cmdCMDCLtPrdt As New OleDb.OleDbCommand
        cmdCMDCLtPrdt.Connection = CN
 
        cmdCMDCLtPrdt.CommandText = "insert into Commandes(NumCommande,DateCommande,NumClient,Description_Commande)" & _
                                           "values('" & txtNCdclt.Text & "','" & dateCmdClt.Text & "','" & txtnumclient.Text & "','" & txtdescmdClt.Text & "')"
                cmdCMDCLtPrdt.ExecuteNonQuery()
        IdAutoCommandeCltPrdt()
        CN.Close()
    End Sub

2nd: procedure adding in details de commande:
VB
Public Sub AddDetailCommande(ByVal Reference As Integer, ByVal NumCommande As Integer, ByVal Prix_unitaire As Double, ByVal Quantite As Integer, ByVal PVenteHT As Double, ByVal taux As Integer, ByVal TVA As Integer, ByVal PrixVenteTTC As Double, ByVal Remise As Integer, ByVal MontantTotPrixVente As Double)
 
        If CN.State = ConnectionState.Closed Then
            CN.Open()
        End If
         Dim cmdDetailcd As New OleDb.OleDbCommand
 
 
        cmdDetailcd.Connection = CN
        cmdDetailcd.CommandText = "insert into Details_commandes(Reference,NumCommande,Prix_unitaire,Quantite,PVenteHT,Taux,TVA,PrixVenteTTC,Remise,MontantTotPrixVente)" & _
                                          "values('" & txtIRefproduit.Text & "','" & txtNCdclt.Text & "','" & txtPrix.Text & "','" & txtQte.Text & "','" & txtPVHT.Text & "','" & txtTaux.Text & "','" & txtTVA.Text & "','" & txtPVTTC.Text & "','" & txtRemise.Text & "','" & txtTMntTTC.Text & "')"
 
 
        cmdDetailcd.ExecuteNonQuery()
 
 
 
        CN.Close()
    End Sub

3rd: Call two procedure by clicking a button:
VB
Private Sub btnAddCommande_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddCommande.Click
     'ajouter donnée dans commande
     Dim i As Integer
     AddCommande(txtNCdclt.Text, dateCmdClt.Value, txtnumclient.Text, txtdescmdClt.Text)

     'jouter dans details de commande

     Dim Reference As Integer
     Dim NumCommande As Integer
     Dim Prix_unitaire As Double
     Dim Quantite As Integer
     Dim PVenteHT As Double
     Dim taux As Integer
     Dim TVA As Integer
     Dim PrixVenteTTC As Double
     Dim Remise As Integer
     Dim MontantTotPrixVente As Double

     For i = 0 To dgvProduits.Rows.Count - 1

         Reference = Convert.ToInt32(dgvProduits.Rows(i).Cells(0).Value)
         NumCommande = Convert.ToInt32(txtNCdclt.Text).ToString
         Prix_unitaire = dgvProduits.CurrentRow.Cells(2).Value
         Quantite = dgvProduits.Rows(i).Cells(3).Value
         PVenteHT = dgvProduits.Rows(i).Cells(4).Value
         taux = dgvProduits.Rows(i).Cells(5).Value
         TVA = dgvProduits.Rows(i).Cells(6).Value
         PrixVenteTTC = dgvProduits.Rows(i).Cells(7).Value
         Remise = dgvProduits.Rows(i).Cells(8).Value
         MontantTotPrixVente = dgvProduits.Rows(i).Cells(9).Value

         AddDetailCommande(Reference, NumCommande, Prix_unitaire, Quantite, PVenteHT, taux, TVA, PrixVenteTTC, Remise, MontantTotPrixVente)

     Next
     MsgBox("Le commande a été ajouté avec succée !!!", vbInformation + vbOKOnly, "Information ")

 End Sub


when i call the first 1 every thing is ok
but the second doesn't work
VB
cmdDetailcd.CommandText = "insert into Details_commandes(Reference,NumCommande,Prix_unitaire,Quantite,PVenteHT,Taux,TVA,PrixVenteTTC,Remise,MontantTotPrixVente)" & _
                                     "values('" & txtIRefproduit.Text & "','" & txtNCdclt.Text & "','" & txtPrix.Text & "','" & txtQte.Text & "','" & txtPVHT.Text & "','" & txtTaux.Text & "','" & txtTVA.Text & "','" & txtPVTTC.Text & "','" & txtRemise.Text & "','" & txtTMntTTC.Text & "')"

cmdDetailcd.ExecuteNonQuery()


thank you
Posted
Comments
Richard Deeming 20-Aug-15 14:59pm    
Your code is vulnerable to SQL Injection[^].

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
adoul1 20-Aug-15 15:07pm    
thanks but how toexplain that the first (1: procedure add commande) it work but the second no!!!!
Richard Deeming 20-Aug-15 15:15pm    
Probably because one of the unvalidated textbox values you're concatenating into your command has escaped from the "data" realm and entered the "code" realm. If you use parameterized queries, that can't happen, so your problem will almost certainly be fixed.

Also, you seem to be ignoring the parameters that you've passed to the methods, and directly accessing the controls instead.

A very likely reason is that since you concatenate the values directly into the SQL statement you suffer from conversion problems. For example dates and numbers must be entered into the fields in the exact format that the database expects them to be for implicit conversion to succeed.

This is not what user wants so you should be able enter the values with local formatting.

Parameters will correct this problem as they also will keep you safe from SQL injections.

For more explanations, have a look at Properly executing database operations[^] and especially Properly executing database operations, version 3[^]
 
Share this answer
 
Comments
adoul1 20-Aug-15 17:20pm    
thank you every one for help: but after i followed your remarks igot this errors: You can not add or change a record because the related record is required in the table "Commandes".
Start by fixing the SQL Injection[^] vulnerability in your code.

Use the parameters passed to the methods, rather than ignoring them and accessing the controls directly.

Create the OleDbConnection object when you need it, and throw it away as soon as you're finished with it. There's no need to keep a connection object hanging around in a field.

Wrap your OleDbConnection and OleDbCommand objects in Using blocks, to ensure that they are always cleaned up properly.

Something like this should work:
VB.NET
Private Function CreateConnection() As OleDbConnection
    Return New OleDbConnection("YOUR CONNECTION STRING HERE")
End Function

Public Sub AddCommande(ByVal NumCommande As Integer, ByVal DateCommande As Date, ByVal NumCLient As Integer, ByVal Description_Commande As String)
    Using connection As OleDbConnection = CreateConnection()
        Using command As New OleDbCommand("insert into Commandes (NumCommande, DateCommande, NumClient, Description_Commande) VALUES (?, ?, ?, ?)", connection)
            ' OleDb doesn't use named parameters, so only the order matters here:
            command.Parameters.AddWithValue("NumCommande", NumCommande)
            command.Parameters.AddWithValue("DateCommande", DateCommande)
            command.Parameters.AddWithValue("NumClient", NumClient)
            command.Parameters.AddWithValue("Description_Commande", Description_Commande)
            
            connection.Open()
            command.ExecuteNonQuery()
        End Using
    End Using
End Sub

Public Sub AddDetailCommande(ByVal Reference As Integer, ByVal NumCommande As Integer, ByVal Prix_unitaire As Double, ByVal Quantite As Integer, ByVal PVenteHT As Double, ByVal taux As Integer, ByVal TVA As Integer, ByVal PrixVenteTTC As Double, ByVal Remise As Integer, ByVal MontantTotPrixVente As Double)
    Using connection As OleDbConnection = CreateConnection()
        Using command As New OleDbCommand("insert into Details_commandes(Reference, NumCommande, Prix_unitaire, Quantite, PVenteHT, Taux, TVA, PrixVenteTTC, Remise, MontantTotPrixVente) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", connection)
            ' OleDb doesn't use named parameters, so only the order matters here:
            command.Parameters.AddWithValue("Reference", Reference)
            command.Parameters.AddWithValue("NumCommande", NumCommande)
            command.Parameters.AddWithValue("Prix_unitaire", Prix_unitaire)
            command.Parameters.AddWithValue("Quantite", Quantite)
            command.Parameters.AddWithValue("PVenteHT", PVenteHT)
            command.Parameters.AddWithValue("Taux", taux)
            command.Parameters.AddWithValue("TVA", TVA)
            command.Parameters.AddWithValue("PrixVenteTTC", PrixVenteTTC)
            command.Parameters.AddWithValue("Remise", Remise)
            command.Parameters.AddWithValue("MontantTotPrixVente", MontantTotPrixVente)
            
            connection.Open()
            command.ExecuteNonQuery()
        End Using
    End Using
End Sub

Private Sub Sub IdAutoCommandeCltPrdt()
    Using connection As OleDbConnection = CreateConnection()
        Using command As New OleDbCommand("select Max(NumCommande) from Commandes", connection)
            connection.Open()
            Dim num As Object = command.ExecuteScalar()
            If num Is Nothing OrElse Convert.IsDBNull(num) Then
                txtNCdclt.Text = "1"
            Else
                txtNCdclt.Text = Convert.ToInt32(num) + 1
            End If
        End Using
    End Using
End Sub

Private Sub btnAddCommande_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddCommande.Click
    Dim NumCommande As Integer = Convert.ToInt32(txtNCdclt.Text)
    AddCommande(NumCommande, dateCmdClt.Value, txtnumclient.Text, txtdescmdClt.Text)
    
     Dim Reference As Integer
     Dim Prix_unitaire As Double
     Dim Quantite As Integer
     Dim PVenteHT As Double
     Dim taux As Integer
     Dim TVA As Integer
     Dim PrixVenteTTC As Double
     Dim Remise As Integer
     Dim MontantTotPrixVente As Double
     
     For i = 0 To dgvProduits.Rows.Count - 1
         Reference = Convert.ToInt32(dgvProduits.Rows(i).Cells(0).Value)
         Prix_unitaire = Convert.ToDouble(dgvProduits.CurrentRow.Cells(2).Value)
         Quantite = Convert.ToInt32(dgvProduits.Rows(i).Cells(3).Value)
         PVenteHT = Convert.ToDouble(dgvProduits.Rows(i).Cells(4).Value)
         taux = Convert.ToInt32(dgvProduits.Rows(i).Cells(5).Value)
         TVA = Convert.ToInt32(dgvProduits.Rows(i).Cells(6).Value)
         PrixVenteTTC = Convert.ToDouble(dgvProduits.Rows(i).Cells(7).Value)
         Remise = Convert.ToInt32(dgvProduits.Rows(i).Cells(8).Value)
         MontantTotPrixVente = Convert.ToDouble(dgvProduits.Rows(i).Cells(9).Value)
         
         AddDetailCommande(Reference, NumCommande, Prix_unitaire, Quantite, PVenteHT, taux, TVA, PrixVenteTTC, Remise, MontantTotPrixVente)
     Next
	 
	 IdAutoCommandeCltPrdt()
     MsgBox("Le commande a été ajouté avec succée !!!", vbInformation + vbOKOnly, "Information ")
End Sub




Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
SQL injection attack mechanics | Pluralsight [^]
 
Share this answer
 
v2
Comments
adoul1 20-Aug-15 17:14pm    
thank you every one for help:
but after i followed your remarks igot this errors:

You can not add or change a record because the related record is required in the table "Commandes".
Richard Deeming 21-Aug-15 9:40am    
That error suggests there's a foreign key relationship between the Details_commandes and Commandes tables.

Your AddCommande method will need to retrieve the primary key of the new record. You'll need to pass that value to the AddDetailCommande method and insert it into the relevant column.

If the primary key is an auto-increment field, you can use SELECT @@IDENTITY to retrieve the new primary key value.

If you need more help, you'll need to provide the table definitions.
adoul1 21-Aug-15 11:19am    
thank you,
this my our table with definitions:
Table Commande:
NumCommande As Integer primary key not auto-increment
DateCommande Date
NumClient As Integer foreign key from Table Client
Description_Commande

Table DetailsCommandes:
Reference As Integer foreign key not auto-increment from Table Produit
NumCommande As Integer foreign key not auto-increment from Table Commande
Prix_unitaire As Double
Quantite As Integer
PVenteHT As Double
taux As Integer
TVA As Integer
PrixVenteTTC As Double
Remise As Integer
MontantTotPrixVente As Double

I done a sub to increment New Commande
Sub IdAutoCommandeCltPrdt()
Try
If CN.State = ConnectionState.Closed Then
CN.Open()
End If
'selection les données à la table commande
Dim cmdCMDCLtPrdt As New OleDb.OleDbCommand("select Max(NumCommande)from Commandes", CN)
' cmd.CommandText =
cmdCMDCLtPrdt.ExecuteNonQuery()
Dim drcmdCMDCLtPrdt As OleDbDataReader = cmdCMDCLtPrdt.ExecuteReader
If drcmdCMDCLtPrdt.Read = True Then
Me.txtNCdclt.Text = drcmdCMDCLtPrdt.Item(0) + 1
Else
Exit Sub
End If
CN.Close()
Catch ex As Exception

End Try
End Sub

Richard Deeming 21-Aug-15 11:25am    
Aha! You're calling the IdAutoCommandeCltPrdt method at the end of the AddCommande method, which increments the value in the textbox. You're then passing the value from the textbox to the AddDetailCommande method, which is then incorrect.

Move the IdAutoCommandeCltPrdt to the end of the process, and store the NumCommande value in a variable outside of the loop.

I'll update my answer with the changes.
adoul1 21-Aug-15 11:31am    
sorry i didn't catch what you mean!
In French !

Ton problème viens des valeurs que tu veux faire entrer dans ta base.
", # et -- ont des significations spéciales en SQL et cassent ta jolie construction.

Recommandation: suivi les coseils de solutions 1 et 2
 
Share this answer
 
Comments
adoul1 20-Aug-15 17:21pm    
thank you every one for help: but after i followed your remarks igot this errors: You can not add or change a record because the related record is required in the table "Commandes".
Patrice T 20-Aug-15 17:30pm    
Avec SQL, certains champs n'ont pas le droit d'avoir 2 fois la même valeur.
C'est la cas pour le champs qui fait le lien entre "Commandes" et "Détails" (dans la table "Commande"
adoul1 20-Aug-15 17:38pm    
mais comment je peux proceder?
commande contient (NumCommande DateCommande NumClient Description_Commande NomVendeur)

details de commandes contient (Reference NumCommande Prix_unitaire Quantite PVenteHT Taux TVA PrixVenteTTC Remise MontantTotPrixVente)
et clients (NumClient Prenom Nom Adresse Region Ville Telephone Faxe
)

Patrice T 20-Aug-15 17:44pm    
Tu ne peux pas créer une seconde commande avec le même numéro.
Tu ne peux pas effacer une commande tant qu'il y a du détail dans l'autre table.
Pour effacer une commande, ty doit dabord effacer chaque ligne de détail de cette commande.
adoul1 20-Aug-15 17:51pm    
en fait j'ai creer un procedure pour l'unicite de clé de nouvl commande:
Sub IdAutoCommandeCltPrdt()
Try
'ouvrir la connection si est fermé
If CN.State = ConnectionState.Closed Then
CN.Open()
End If
'selection les données à la table commande
Dim cmdCMDCLtPrdt As New OleDb.OleDbCommand("select Max(NumCommande)from Commandes", CN)
' cmd.CommandText =
cmdCMDCLtPrdt.ExecuteNonQuery()
Dim drcmdCMDCLtPrdt As OleDbDataReader = cmdCMDCLtPrdt.ExecuteReader
If drcmdCMDCLtPrdt.Read = True Then
Me.txtNCdclt.Text = drcmdCMDCLtPrdt.Item(0) + 1
Else
Exit Sub
End If

CN.Close()
Catch ex As Exception

End Try
End Sub
je peux faire l'insertion de donnée dans les deux table commande et détails de commande mais toujour j'ai reçu cette erreur

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900