【发布时间】:2017-12-04 17:50:13
【问题描述】:
我有一个 GetUSerID 函数,它运行 SQL 查询来获取 UserID。查询有效并返回一个 userID,但我认为它没有应用 WHERE 条件。 IT 只返回用户表中最高的用户 ID。 (我通过添加一个新用户(因此更改了最高用户 ID)然后再次登录来测试这一点 - 并且显示的用户 ID 增加到现在最高的用户 ID。我相信它只是在做“从用户中选择用户 ID”并抓住第一个结果和“WHERE username =”没有被应用。我知道我用于获取用户名的过程有效 - 当我将其声明为变量并立即显示它时 - 用户名是正确的 - 但它不显示与该用户名一起使用的 userRID。
我正在寻找一种方法来查看在我运行应用程序时传递给 SQL 的确切查询。无论如何,Visual Studio 2015 中是否有在调试模式下运行 SQL 跟踪或其他东西?
代码是……
Private Function GetUserID(userName As String) As Integer
Dim userId As Integer
Using con As New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\BandDatabase.mdf;Integrated Security=True")
Dim comm As New SqlCommand("select UserID from Users where username = userName", con)
comm.Parameters.AddWithValue("userName", userName)
comm.CommandType = CommandType.Text
con.Open()
Try
Dim reader As SqlDataReader = comm.ExecuteReader()
If reader.HasRows Then
While (reader.Read)
userId = reader.GetInt32(0)
End While
reader.Close()
Return userId
Else
'no user found
Return -1
End If
Catch e As Exception
Throw New Exception("An exception has occurred: " + e.Message)
Finally
con.Close()
End Try
End Using
End Function
我知道用户名有效,因为我可以这样称呼它...
userName = System.Web.HttpContext.Current.User.Identity.Name
它会选择正确的名称。
但是,当我在页面加载中调用我的函数来显示...时(如下所示),它只会获取最高的用户 ID...
Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim userID As Integer = GetUserID(System.Web.HttpContext.Current.User.Identity.Name)
'Displays a correct looking userID but not sure it is updating correctly
lblStudent.Text = userID
End Sub
【问题讨论】:
-
调试>Windows>本地。但是您的查询没有传递字符串或变量,而是将列
username与自身进行比较,这将返回所有行。 -
在 pageLoad 调用它会不会改变 SQL 中正在查看的内容? Dim userID As Integer = GetUserID(System.Web.HttpContext.Current.User.Identity.Name)
-
专注于我所说的,它与页面加载无关。
select UserID from Users where username = userName这两个用户名值是列引用,您的数据未传递给此查询。您正在选择用户名列等于自身的用户 ID。总是这样。因此,为什么您会在表中获得最新的记录 ID。在 SQL 中尝试一下,你会看到。您需要在vb代码中使用“@username”作为参数。 -
@RobertvonMehren - 听听 Jacob H 告诉你什么。他是对的。您的查询不正确。
标签: mysql asp.net vb.net visual-studio-2015