【问题标题】:What's wrong with my Count Query asp.net我的计数查询 asp.net 有什么问题
【发布时间】:2016-01-03 13:06:52
【问题描述】:
Public state_name as String
state_name = Textbox1.Text

Dim constr As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
Dim query As String = "SELECT Count(cities) FROM state_table WHERE state_name=" & state_name
Using conn As New SqlConnection(constr)
    Using comm As New SqlCommand()
        conn.Open()
        With comm
            .Connection = conn
            .CommandText = query
            .CommandType = CommandType.Text
        End With

        Dim count As Int16 = Convert.ToInt16(comm.ExecuteScalar())
        Label1.Text = count
    End Using
End Using

代码显示错误

列名“加利福尼亚”无效。

但是California 已经出现在我的State 表中,我想计算我在State 表中输入的state_name= california 下的所有城市。

我希望输出为

California (3)

【问题讨论】:

  • 使用参数化查询而不是将参数连接到 SQL 字符串中。
  • 添加...state_name='" & state_name &"'"
  • 无论使用引号还是将它们添加到您的 var state_name 中

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


【解决方案1】:

你想使用参数化查询来避免SQL Injection.

Dim constr As String = ConfigurationManager.ConnectionStrings("ApplicationServices").ConnectionString
Dim query As String = "SELECT Count(cities) FROM state_table WHERE state_name=@State_Name"
Using conn As New SqlConnection(constr)
   Using comm As New SqlCommand()
      conn.Open()
      With comm
         .Connection = conn
         .CommandText = query
         .CommandType = CommandType.Text
         .Parameters.AddWithValue("@State_Name", state_name)
      End With
      Dim count As Int16 = Convert.ToInt16(comm.ExecuteScalar())
      Label1.Text = count
   End Using
End Using

【讨论】:

    【解决方案2】:

    因为您没有用引号将变量括起来。 "state_name = '" + state_name + "'"

    但是,您应该改用参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 2010-12-23
      • 2010-11-26
      • 2017-02-25
      • 2010-09-29
      • 1970-01-01
      相关资源
      最近更新 更多