Question

I have some problem is my code VB.Net : I have this function :

 Public Shared Function AfficherResultat(ByVal _region As Double, ByVal _datvente As DateTime, ByVal _speculation As String) As DataSet
        Dim ds As DataSet
        Dim cnn As SqlConnection = OuvrirConnection()
        Dim dscmd As SqlDataAdapter
        Dim sql As String = "select * from traitementprix where ( region =" + _region.ToString() + " and Datvente = " + _datvente.ToString() + " and speculation = N'" + _speculation + "')"
        dscmd = New SqlDataAdapter(sql, cnn)
        ds = New DataSet()
        dscmd.Fill(ds, "traitementprix")
        Return ds
    End Function

i got an error in this line

dscmd.Fill(ds, "traitementprix")

the error is Incorrect syntax near '00'.

I'm not familair with the Vb.net syntax and i don't find the solution.

  1. What is the reason of this error?
  2. How can i fix it?
Was it helpful?

Solution

The reason of your error is probably the presence of a single quote in one or more of your strings values. Concatenated together with the rest of the sql text, the single quote breaks the sql syntax.

As suggested you should use a parameterized query where this problem is handled for you by the framework code

 Dim sql As String = "select * from traitementprix where ( region =@rgn and " & _
                     "Datvente = @dt and speculation = @spec)"
 dscmd = New SqlDataAdapter(sql, cnn)
 dscmd.SelectCommand.Parameters.AddWithValue("@rgn", _region)
 dscmd.SelectCommand.Parameters.AddWithValue("@dt", _datvente)
 dscmd.SelectCommand.Parameters.AddWithValue("@spec", _speculation)
 ds = New DataSet()
 dscmd.Fill(ds, "traitementprix")

An important thing to note: I don't know the exact data type for fields listed above. When you use the AddWithValue method you need to pass exactly a value of the corresponding datatype expected by the field. So, for example, if the field region is a number and the variable _region is a string, then a conversion is required

 dscmd.SelectCommand.Parameters.AddWithValue("@rgn", Convert.ToInt32(_region))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top