我正在尝试从MS-Access数据库中检索记录数据并将其存储到变量中。
我正在使用此SQL命令查询数据库:
Dim cmdRead As OleDbCommand = New OleDbCommand("SELECT UserID FROM [User] where Username=?", conn)
如何在VB.NET中从UserID列(在db中)读取数据并将其存储到VB.NET中的变量中?
我基本上想要做的是检索UserID,以便我可以从同一个表中检索用户的姓名和姓氏。
注意:我正在使用ASP.NET与Web Develop 2003和MS-Access 2003 db。
这是完整的代码:
Imports System.Data.OleDb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\WebSite3\db.mdb;")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT Username, Password FROM [User] where Username=? and Password=?", conn)
cmd.Parameters.AddWithValue("@Username", txtUsername.Text)
cmd.Parameters.AddWithValue("@Password", txtPassword.Text)
Try
conn.Open()
Dim read As OleDbDataReader = cmd.ExecuteReader()
If read.HasRows Then
While read.Read()
If txtUsername.Text = read.Item("username").ToString And txtPassword.Text = read.Item("password").ToString Then
Dim tID As Long = read.Item("UserID").ToString
Dim tName As String = read.Item("CustomerName").ToString
Dim tSurname As String = read.Item("CustomerSurname").ToString
lblLogged.Text = lblLogged.Text + tName + tSurname
lblLogged.Visible = True
End If
End While
Else
lblLogged.Text = "Login unsuccessful"
End If
read.Close()
Catch ex As Exception
Response.Write(ex.Message())
Finally
conn.Close()
End Try
End Sub
End Class
答案 0 :(得分:0)
你的例子中有些东西乱了。请试试这个。
首先更改OleDbCommand以检索userID,当您从同一个表中读取时我不需要第二个命令,我认为UserName和Password标识了一个唯一的用户
Dim cmd As OleDbCommand = New OleDbCommand("SELECT UserID, Username, Password FROM [User] where Username=? and Password=?", conn)
然后添加您的参数并查询数据库
Try
conn.Open()
Dim read As OleDbDataReader = cmd.ExecuteReader()
If read.HasRows Then
read.Read()
' Now you can read the Item and pass the values to your textboxes
txtUsername.Text = read.Item("username").ToString
txtPassword.Text = read.Item("password").ToString
txtUserID.Text = read.Item("userid").ToString
Else
lblLogged.Text = "Login unsuccessful"
End If
read.Close()
Catch ex As Exception
Response.Write(ex.Message())
Finally
conn.Close()
End Try
答案 1 :(得分:0)
这应该在你的试用版
中conn.Open()
Dim read As OleDbDataReader = cmd.ExecuteReader()
If read.HasRows Then
While read.Read()
If txtUsername.Text = read.Item("username").ToString And txtPassword.Text = read.Item("password").ToString Then
Dim tID as long = read.Item("UserID").ToString
Else
lblLogged.Text = "Login unsuccessful"
End If
End While
End If
在最后一块
中read.Close()