gpt4 book ai didi

mysql - ASP.net - VB NET 如何计算 SQL 查询的行数

转载 作者:行者123 更新时间:2023-11-29 22:54:09 24 4
gpt4 key购买 nike

大家好,我对 ASP.net 非常陌生,正在尝试构建一个我认为简单的重定向页面。我已经有了 IIS 基本身份验证设置,成功登录后,用户将到达下面的 default.aspx 页面。我有一个数据库,我在其中创建了用户登录的副本并为它们创建了 group_id。我想要做的是,成功登录后,用户将到达下面的默认页面,并检查该用户是否属于 group_ID 1001,答案是"is",将其重定向到 URL1,如果不是,则将其重定向到 URL2。

我从这个网站上的人们那里得到了很多帮助,并给了我关于不同编码语言的例子,我认为我可以轻松翻译它们,但总是陷入不同的步骤。现在我收到以下错误,并一直在努力理解其中的逻辑。希望从 VB Net 专家那里获得一些建议。非常感谢帮助,但现在已经坚持了好几天了,哈哈。

更新代码 - 3 月 1 日

%@ Page Language="VB" debug="true" %>
<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "MySql.Data.MySqlClient" %>
<script language="VB" runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim username As String = Convert.ToString(User.Identity.Name.Substring(User.Identity.Name.IndexOf("\") + 1))
Dim myConnection As MySqlConnection
Dim myDataAdapter As MySqlDataAdapter
Dim strSQL As String
Dim mySqlCommand As MySqlCommand
Dim counter As Integer
Dim isInGroup As Boolean

myConnection = New MySqlConnection("server=localhost; user id=Directory_Admin; password=IMCisgreat2014; database=imc_directory_tool; pooling=false;")
strSQL = "SELECT COUNT(*) FROM tbl_staff WHERE username = @username AND 'group_id' = '1001';"
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)

mySqlCommand = New MySqlCommand(strSQL)
mySqlCommand.Parameters.AddWithValue("@username", username)
counter = mySqlCommand.ExecuteScalar()
myConnection.Open()
If isInGroup = counter > 0 Then
Response.Redirect("http://www.w3schools.com")
Else
Response.Redirect("http://www.google.ca")
End If
myConnection.Close()
End Sub

</script>

<html>
<head>
<title>Simple MySQL Database Query</title>
</head>
<body>

Main page ...

</body>
</html>

我收到以下错误:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Connection must be valid and open.

Line 18: mySqlCommand = New MySqlCommand(strSQL)
Line 19: mySqlCommand.Parameters.AddWithValue("@username", username)
Line 20: counter = mySqlCommand.ExecuteScalar()
Line 21: If isInGroup = counter > 0 Then
Line 22: Response.Redirect("http://www.w3schools.com")

最佳答案

您创建了一个 MySqlConnection,但从未将 MySqlCommand 连接到它。

mySqlCommand.Connection = mySqlConnection
mySqlCommand.Connection.Open()

此外,在调用 ExecuteScalar 之后,不要忘记关闭连接

mySqlCommand.Connection.Close()

否则您将拥有一个处于打开状态且悬空的连接。

关于mysql - ASP.net - VB NET 如何计算 SQL 查询的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28789865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com