Oledb连接SQL命令

时间:2016-12-14 15:40:16

标签: vb.net oledb

Private Sub Myconnection()

    con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\Users.accdb")
    con.Open()
End Sub

Private Sub Login_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Myconnection()
End Sub

Private Sub LoginButton_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
    Dim userTable As New DataTable
    Myconnection()
    adapt = New OleDbDataAdapter("Select * From Registered Users Where User Name='" & UserNameTextBox.Text & "'And Password='" & PasswordTextBox.Text & "'", con)
    adapt.Fill(userTable)

    If userTable.Rows.Count > 0 Then
        MsgBox("Login Succesful")

    Else
        MsgBox("User Name Or Password Is invalid")
    End If
End Sub

当我运行上面的代码时,目前我收到此错误“附加信息:查询表达式中的语法错误(缺少运算符)'用户名='用户'和密码='密码''。”我应该如何更改我的代码才能使其正常工作

1 个答案:

答案 0 :(得分:0)

这应该可行,在这里我使用一个带有函数的类,该函数接受使用参数传递给命令的用户名和密码。不需要DataTable,只需使用HasRows来确定是否已返回数据。

Imports System.Data.OleDb
Public Class DataOperations
    Private Builder As New OleDb.OleDbConnectionStringBuilder With
        {
            .Provider = "Microsoft.ACE.OLEDB.12.0",
            .DataSource = IO.Path.Combine(Application.StartupPath, "Users.accdb")
        }
    ''' <summary>
    ''' Determine if a user and password are located in the Registered Users table.
    ''' </summary>
    ''' <param name="UserName">User name</param>
    ''' <param name="UserPassword">user password</param>
    ''' <returns></returns>
    Public Function IsValidUser(ByVal UserName As String, ByVal UserPassword As String) As Boolean
        Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
            Using cmd As New OleDbCommand With {.Connection = cn}
                cmd.CommandText = "SELECT [User Name] FROM [Registered Users] WHERE [User Name] = @UserName AND [Password] = @Password"
                cmd.Parameters.AddWithValue("@UserName", UserName)
                cmd.Parameters.AddWithValue("@Password", UserPassword)
                cn.Open()
                Dim reader As OleDbDataReader = cmd.ExecuteReader
                Dim result = reader.HasRows
                reader.Close()
                Return result
            End Using
        End Using
    End Function
End Class

用法

Dim ops As New DataOperations
If ops.IsValidUser(UserNameTextBox.Text, PasswordTextBox.Text) Then
    MessageBox.Show("Known user")
Else
    MessageBox.Show("Guards, intruder alert!!!")
End If