我有一个 GetUSerID 函数,它运行一个 SQL 查询来获取 UserID。该查询有效并返回一个 userID,但我认为它没有应用 WHERE 条件。 IT 只是返回 Users 表中最高的 UserID。 (我通过添加一个新用户(因此更改了最高用户 ID)然后再次登录来对此进行测试 - 并且显示的用户 ID 增加到现在最高的用户 ID。我相信它只是在做“从用户中选择用户 ID”并获取第一个结果和“WHERE username=”没有被应用。我知道我用来获取用户名的过程是有效的——当我声明它是一个变量并立即显示它时——用户名是正确的——但它不显示与该用户名一起使用的 useRID。
我正在寻找一种方法来查看在我运行应用程序时传递给 SQL 的确切查询。在 Debug模式下,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
最佳答案
要继续使用参数,请正确使用参数。注意添加的 @
Dim comm As New SqlCommand("select UserID from Users where username = @userName", con)
comm.Parameters.AddWithValue("@userName", userName)
如果没有 @
,您的查询只是在表单中
SELECT A.B FROM A WHERE A.C = A.C
这只会返回整个表,并且在您的代码中,因为您迭代结果并返回最后一个结果,所以它只会返回表中最后一行的 UserID
。
关于mysql - 如何查看从 VB.net 代码传递给 SQL 的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47639143/