如何检查Access数据库中是否存在记录

时间:2012-07-16 19:47:53

标签: database vb.net ms-access login oledb

我正在为我正在开发的项目尝试一种新方法,我刚开始学习Access数据库。我使用 VB.net ,我的问题是:如何查看数据库表中是否存在记录。我以为我明白了,但事实并非如此。我正在创建一个登录名,我希望它在尝试比较您输入的内容与数据库中的内容之前检查他们输入的用户名是否存在。我看到很多关于如何做到这一点的问题...但不是对于VB.net MS Access

这是我的代码:

Imports System.Data.OleDb
Public Class LoginForm1
    Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Public myConnection As OleDbConnection = New OleDbConnection
    Public dr As OleDbDataReader
    Dim Errors As String
    Public Sub AccessAccountDatabase()
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
        dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
        Errors = ""
        Try
            myConnection.Open()
            Dim str As String
            str = "SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & "' AND Password='" & PasswordTxt.Text & "'"
            Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
            dr = cmd.ExecuteReader
            dr.Read()

            If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
                Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
                MsgBox("Welcome back " & dr("Real_Name") & "!")
            Else
                MsgBox("Login Failure")
            End If
            myConnection.Close()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub OkayBtn_Click(sender As System.Object, e As System.EventArgs) Handles OkayBtn.Click
        AccessAccountDatabase()
    End Sub
End Class

所以现在我的问题是......如何检查数据库中是否存在记录,因为当您键入正确的信息(数据库中存在正确的用户名和密码)时,它表示欢迎和所有。但是当您键入错误的用户名和/或密码时,它不起作用。如果没有“Try Catch”语句,程序就会冻结。使用try catch,它说明了这一点:

System.InvalidOperationException: No data exists for the row/column.
   at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal)
   at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal)
   at System.Data.OleDb.OleDbDataReader.get_Item(String name)
   at CybSol_Journal_Database.LoginForm1.AccessAccountDatabase() in c:\users\richard\documents\visual studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\LoginForm1.vb:line 36

补充信息:第36行是:If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then

5 个答案:

答案 0 :(得分:7)

第一个问题:

Access中的

PASSWORD is a reserved keyword。你应该用方括号括起来:

"SELECT * FROM Accounts WHERE Username='" & UsernameTxt.Text & _
"' AND [Password]='" & PasswordTxt.Text & "'" 

第二个问题:

永远不要使用字符串连接来创建sql文本。总是使用参数

 str = "SELECT * FROM Accounts WHERE Username=? AND [Password]=?"   
 Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)   
 cmd.Parameters.AddWithValue("user", UserNameTxt.Text)
 cmd.Parameters.AddWithValue("pass", PasswordTxt.Text)
 dr = cmd.ExecuteReader   

为什么呢? look here如果从用户输入连接字符串

会发生什么

第三个问题:测试命令是否返回行

 If dr.Read() Then
    ......

 End if  

答案 1 :(得分:2)

我添加了一些Using语句,因此您无需手动关闭连接。另外,我参数化了SQL语句以防止SQL注入。

 Public Class LoginForm1
      Dim provider As String
      Dim dataFile As String
      Dim connString As String
      'Public myConnection As OleDbConnection = New OleDbConnection
      'Public dr As OleDbDataReader
      Dim Errors As String
      Public Sub AccessAccountDatabase()
        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
        dataFile = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\CybSol Journal Database\CybSol Journal Database\cgi-bin\Data.mdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
        Errors = ""
        Try
          Using myConnection As OleDbConnection = New OleDbConnection(connString)
            myConnection.Open()
            Dim str As String
            str = "SELECT * FROM Accounts WHERE Username=@USER AND [Password]=@PWD "
            Using cmd As OleDbCommand = New OleDbCommand(str, myConnection)
              cmd.Parameters.AddWithValue("@USER", UsernameTxt.Text)
              cmd.Parameters.AddWithValue("@PWD", PasswordTxt.Text)
              Using dr As OleDbDataReader = cmd.ExecuteReader
                If dr.HasRows Then
                  dr.Read()
                  If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
                    Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
                    MsgBox("Welcome back " & dr("Real_Name") & "!")
                  Else
                    MsgBox("Login Failure")
                  End If
                Else
                  MsgBox("Login Failure")
                End If
              End Using
            End Using
          End Using
        Catch ex As Exception
          MsgBox(ex.ToString)
        End Try


      End Sub

      Private Sub OkayBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OkayBtn.Click
        AccessAccountDatabase()
      End Sub
    End Class

答案 2 :(得分:1)

你走在正确的轨道上。 OleDbDataReader.Read返回一个布尔值,表示它是否成功读取了现有行。因此,您可以在尝试读取记录之前检查它是否返回True。例如:

If dr.Read() Then
    If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then
    Dim Welcome As String = "SELECT * FROM Accounts WHERE Real_Name=" & "Username"
        MsgBox("Welcome back " & dr("Real_Name") & "!")
    Else
        MsgBox("Login Failure")
    End If
End If

此外,我觉得至少应该提一下,以纯文本格式存储密码永远不是一个好主意。

答案 3 :(得分:0)

您不必再次检查代码中的用户名和密码,因为如果在数据库中不匹配,则不会返回任何行。

你可以简单地做

dr = cmd.ExecuteReader
If dr.HasRows Then
   //it matched
Else
   //it didn't match. could not log in
End If

如果你仍想保留它,你的方法如下,但没有必要

dr = cmd.ExecuteReader
If dr.HasRows Then

    dr.Read()

    If UsernameTxt.Text = dr("Username").ToString AndAlso PasswordTxt.Text = dr("Password").ToString Then

    Else

    End If

End If

答案 4 :(得分:0)

在DataReader上使用Read()方法(请注意,这会使您与数据库的连接保持打开状态,而当DataReader仍在读取时,您将无法在数据库上执行任何其他命令。

If String.Compare(dr("Username").ToString(), UsernameTxt.Text, true) AndAlso String.Compare(dr("Password").ToString(), PasswordTxt.Text.ToString() Then
    ' The username and password for the record match
    ' the input from the login form
    ProcessLogin()
Else
    ' Invalid username or password, send an error
End If