【问题标题】:Sql error within application应用程序中的 Sql 错误
【发布时间】:2014-03-21 15:08:12
【问题描述】:

我有一些问题是我的代码VB.Net:我有这个功能:

 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

我在这行有一个错误

dscmd.Fill(ds, "traitementprix")

错误是'00'附近的语法不正确。

我不熟悉 Vb.net 语法,也找不到解决方案。

  1. 这个错误的原因是什么?
  2. 我该如何解决?

【问题讨论】:

  • 尝试更改... + " and speculation = 'N" + _speculation + "')"
  • 使用参数化 SQL。首先,这可以很好地解决您当前的问题,其次它有助于防止 SQL 注入攻击。
  • @JonSkeet : 在这个例子中如何使用参数化 SQL?
  • 和平常一样——你尝试过什么,遇到了什么问题?见msdn.microsoft.com/en-us/library/bbw6zyha(v=vs.110).aspx

标签: sql .net vb.net dataset double


【解决方案1】:

您的错误原因可能是您的一个或多个字符串值中存在单引号。单引号与其余 sql 文本连接在一起,会破坏 sql 语法。

按照建议,您应该使用由框架代码为您处理此问题的参数化查询

 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")

需要注意的重要一点:我不知道上面列出的字段的确切数据类型。当您使用 AddWithValue 方法时,您需要准确地传递字段预期的相应数据类型的值。因此,例如,如果字段region 是数字,而变量_region 是字符串,则需要进行转换

 dscmd.SelectCommand.Parameters.AddWithValue("@rgn", Convert.ToInt32(_region))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-25
    • 2014-05-23
    • 2015-04-26
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多