【问题标题】:Problem with querying sql server from vb从vb查询sql server的问题
【发布时间】:2011-06-15 22:41:03
【问题描述】:

只要我有

Dim catID as integer

我在这样的查询中使用它:

cmd.CommandText = "select * from categories where parentid='" + catID + "'"

我明白了:

从字符串select * from categories where p 到类型Double 的转换无效。

为什么会这样?
sql 中的parentid 数据类型为integer

【问题讨论】:

  • 试试这个:cmd.CommandText = "select * from categories where parentid='" + catID.ToString() + "'" 另外,只是一个想法:你正在为 parentid 指定 catid...如果在 SQL Server Management Studio 中,您的上述查询会运行吗?
  • 请始终使用参数化查询,切勿串联字符串。
  • 这个错误信息是从哪里来的?我怀疑它是 SQL Server,因为 Double 数据类型称为 Float。

标签: sql vb.net visual-studio-2010


【解决方案1】:

试试

cmd.CommandText = string.Format("select * from categories where parentid='{0}'", catID)

如果 parentid 是数据库中的数字字段,那么您将需要

cmd.CommandText = string.Format("select * from categories where parentid={0}", catID)

【讨论】:

    【解决方案2】:

    只需去掉单引号:

    cmd.CommandText = "select * from categories where parentid=" + catID.ToString()
    

    【讨论】:

      【解决方案3】:

      错误是告诉您它无法使用您的 catID 值添加“SELECT *...”。 '+' 运算符试图将 "SELECT *..." 转换为一个数字,以便对其进行数学运算,但它不能,所以它抛出了错误。

      很多人尝试使用 '+' 进行字符串连接。这不是最佳实践,因为 '+' 只会在双方都是字符串时连接。但是,如果它在一侧找到一个数字(如您的情况,使用 catID),那么它将尝试进行数学运算而不是 concat。

      养成从不使用“+”连接字符串的习惯的最佳实践;总是使用 '&' 代替。这样你就不用考虑了。

      即:

      1+1 = 2
      1+A = error
      1&1 = 11
      1&A = 1A
      

      【讨论】:

      • 顺便说一句——关于参数化查询的其他 cmets 很重要。就冒着注射的风险而言,您这样做的方式可能很危险。
      • 它是一个内部应用程序,所以不用担心 :),顺便说一句,小费很棒,我现在会记住的 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      • 2015-03-02
      • 2011-05-01
      相关资源
      最近更新 更多