mysql - 如何查看从 VB.net 代码传递给 SQL 的查询

标签 mysql asp.net vb.net visual-studio-2015

我有一个 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/

相关文章:

python - 如何将本地.sql文件导入pythonanywhere数据库?

asp.net - 使用 2 个参数的 SqlDataSource SelectCommand 和 LIKE 不起作用

.net - 无法使用 Visual Basic 将具有 12 位小数的 double /十进制值转换为字符串

java - Ejb sql [select * from where A & 1]

mysql - 按日期对 MYSQL 结果行进行分组

php - 我如何获取post变量的值,通过ajax在php中发送

c# - 您如何手动将复杂对象数据绑定(bind)到模板化控件,例如 gridview 中的一行?

asp.net - 在 GridView 自动数据绑定(bind)中捕获错误

c# - 如何在母版页内的用户控件中获取内容页名称?

mysql - 如何使用 Microsoft Visual Studio 2010 检查列中是否存在值